-
Notifications
You must be signed in to change notification settings - Fork 0
/
DSU_Ashisgup
83 lines (70 loc) · 1.13 KB
/
DSU_Ashisgup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
const int N = 2e5 + 5;
struct DSU
{
int connected;
int par[N], sz[N];
void init(int n)
{
for(int i=1;i<=n;i++)
{
par[i]=i;
sz[i]=1;
}
connected=n;
}
int getPar(int k)
{
if(par[k] == k) return k;
return par[k] = getPar(par[k]);
}
int getSize(int k)
{
return sz[getPar(k)];
}
void unite(int u, int v)
{
// cout << "u: " << u << " v: " << v << endl;
int par1=getPar(u), par2=getPar(v);
// cout << "parU: " << par1 << " parV: " << par2 << endl;
if(par1==par2)
return;
connected--;
if(sz[par1]>sz[par2])
swap(par1, par2);
sz[par2]+=sz[par1];
sz[par1]=0;
par[par1]=par[par2];
}
};
int n;
DSU dsu;
set<int> s[26];
int32_t main()
{
IOS;
cin >> n;
dsu.init(n);
for(int i = 1; i <= n; i++)
{
string str;
cin >> str;
for(auto &it:str)
s[it - 'a'].insert(i);
}
for(int i = 0; i < 26; i++)
{
int prv = 0;
for(auto &it:s[i])
{
if(prv)
dsu.unite(prv, it);
prv = it;
}
}
cout << dsu.connected;
return 0;
}