-
Notifications
You must be signed in to change notification settings - Fork 28
/
foxlings.cpp
63 lines (58 loc) · 985 Bytes
/
foxlings.cpp
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
#include <iostream>
#include <map>
using namespace std;
map<int,int> mp;
map<int,int>siz;
int root(int i)
{
while(i!=mp[i])
{
mp[i]=mp[mp[i]];
i=mp[i];
}
return i;
}
void weightedUnion(int x,int y)
{
int rootX=root(x);
int rootY=root(y);
if(siz[rootX]<siz[rootY])
{
mp[rootX]=mp[rootY];
siz[rootY]+=siz[rootX];
}
else
{
mp[rootY]=mp[rootX];
siz[rootX]+=siz[rootY];
}
}
int main()
{
std::ios::sync_with_stdio(false);
int n,m;
cin>>n>>m;
int ans=n;
while(m--)
{
int x,y;
cin>>x>>y;
if(!mp[x])
{
mp[x]=x;
siz[x]=1;
}
if(!mp[y])
{
mp[y]=y;
siz[y]=1;
}
if(root(x)!=root(y))
{
weightedUnion(x,y);
ans--;
}
}
cout<<ans;
return 0;
}