-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisjointSet.cpp
More file actions
52 lines (48 loc) · 1020 Bytes
/
Copy pathdisjointSet.cpp
File metadata and controls
52 lines (48 loc) · 1020 Bytes
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
#include <bits/stdc++.h>
using namespace std;
int find(int u, int parent[])
{
if (parent[u] < 0)
return u;
return find(parent[u], parent);
}
void unionByWeight(int u, int v, int parent[])
{
int pu = find(u, parent), pv = find(v, parent);
if (pu != pv)
{
if (parent[pu] > parent[pv])
{
parent[pv] += parent[pu];
parent[pu] = pv;
}
else
{
parent[pu] += parent[pv];
parent[pv] = pu;
}
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int V, E;
cin >> V >> E;
int parent[V];
for (int i = 0; i < V; ++i)
parent[i] = -1;
for (int i = 0; i < E; ++i)
{
int s, d;
cin >> s >> d;
unionByWeight(s, d, parent);
}
for (int i = 0; i < V; ++i)
cout << i << " - " << parent[i] << endl;
return 0;
}