-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisjointSetOps.sublime-snippet
77 lines (71 loc) · 1.54 KB
/
DisjointSetOps.sublime-snippet
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
<snippet>
<content><![CDATA[
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define vll vector<ll>
#define F first
#define S second
#define pll pair<ll,ll>
#define FOR1(i,a) for(i=0;i<=a;i++)
#define FOR2(i,a,b) for(i=a;i<=b;i++)
#define endl '\n'
#define clr(a) memset(a,0,sizeof(a))
#define all(x) x.begin(),x.end()
typedef long long ll;
void make_set(vector<ll> &id, vector<ll> &rank, ll n) {
for(ll i=1; i<=n; i++) {
id[i] = i;
rank[i] = 1;
}
}
ll find_set(vector<ll> &id, ll p) {
ll root = p;
//find the root
while(root != id[root]) {
root = id[root];
}
//perform path compression
while(p != root) {
ll newp = id[p];
id[p] = root;
p = newp;
}
return root;
}
void merge_set(vector<ll> &id, vector<ll> &rank, ll x, ll y) {
x = find_set(id, x);
y = find_set(id, y);
if(rank[x] > rank[y])
id[y] = x;
else
id[x] = y;
if(rank[x] == rank[y])
rank[y] += 1;
}
int main()
{
ll n,res=0,e,i;cin>>n>>e;
vector<ll> rank(n+1), id(n+1);
make_set(id,rank,n);
FOR1(i,n-1)
{
ll u,v;
cin>>u>>v;
if(find_set(id,u)!=find_set(id,v))
merge_set(id,rank,u,v);
}
for(i=1;i<=n;i++) {
if(id[i] == i)
res++;
}
cout<<res<<endl;
return 0;
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>disjoinset</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>