-
Notifications
You must be signed in to change notification settings - Fork 0
/
union_find.cpp
59 lines (49 loc) · 896 Bytes
/
union_find.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
#include<bits/stdc++.h>
using namespace std;
map < int , int > parent;
void make_parent1(int n)
{
for (int i=1; i<=n; i++)
{
parent[i]=i;
}
}
void make_parent2(int n)
{
for (int i=1; i<=n; i++)
{
parent[i]=-1;
}
}
int Find(int node)
{
if(parent[node]==-1) return node;
parent[node]=Find(parent[node]);
return parent[node];
}
void Union(int node1, int node2)
{
int a= Find(node1);
int b= Find(node2);
if(a==b) return;
parent[b]=a;
}
int main()
{
int n,i,j,k,l,x,cnt=0;
cin>>n;
make_parent2(n);
for(i=1;i<=n;i++)
{
scanf("%d", &x);
Union(i,x);
}
//number of connected components
map < int, int > :: iterator it;
for(it=parent.begin();it != parent.end();it++)
{
//cout<<(*it).second<<endl;
if((*it).second == -1) cnt++;
}
cout<<cnt<<endl;
}