并查集(算法)

模板

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int f[1000],n,m,k,sum=0;
 4 void chu()
 5 {
 6     int i;
 7     for(int i=1;i<=n;i++)
 8         f[i]=i;//初始化
 9     return;
10 }
11 int find(int v)
12 {
13     if(f[v]==v)
14     return v;
15     else
16     {
17         f[v]=find(f[v]);//找祖先18         return f[v];
19     }
20 }
21 void merge(int v,int u)
22 {
23     int t1,t2;
24     t1=find(v);
25     t2=find(u);
26     if(t1!=t2)
27     {
28         f[t2]=t1;//合并
29     
30     }
31     return;
32 }
33 int main()
34 {
35     int x,i,y;
36     scanf("%d %d",&n,&m);
37     chu();
38     
39     for(i=1;i<=m;i++)
40     {
41         scanf("%d %d",&x,&y);
42         merge(x,y);
43     }
44     for(i=1;i<=n;i++)
45     {
46         if(f[i]==i)
47          sum++;
48     }
49     cout<<sum;
50     return 0;
51 }

猜你喜欢

转载自www.cnblogs.com/ltlt/p/8997000.html
今日推荐