G - Ice_cream's world I (并查集)

点击打开链接

ice_cream's world is a rich country, it has many fertile lands. Today, the queen of ice_cream wants award land to diligent ACMers. So there are some watchtowers are set up, and wall between watchtowers be build, in order to partition the ice_cream’s world. But how many ACMers at most can be awarded by the queen is a big problem. One wall-surrounded land must be given to only one ACMer and no walls are crossed, if you can help the queen solve this problem, you will be get a land.

InputIn the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file. OutputOutput the maximum number of ACMers who will be awarded. 
One answer one line. Sample Input

8 10
0 1
1 2
1 3
2 4
3 4
0 5
5 6
6 7
3 6
4 7

Sample Output

3

AC代码
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 const int maxn=1010;
 8 
 9 int n,m;
10 int father[maxn];
11 
12 void makeSet(){
13     for(int i=0;i<n;i++){
14         father[i]=i;
15     }
16 }
17 
18 int findSet(int x){
19     if(x!=father[x]){
20         father[x]=findSet(father[x]);
21     }
22     return father[x];
23 }
24 
25 int main(){
26 
27     //freopen("input.txt","r",stdin);
28 
29     while(~scanf("%d%d",&n,&m)){
30         makeSet();
31         int ans=0;
32         int a,b;
33         while(m--){
34             scanf("%d%d",&a,&b);
35             int fx=findSet(a);
36             int fy=findSet(b);
37             if(fx==fy)
38                 ans++;
39             else
40                 father[fx]=fy;
41         }
42         printf("%d\n",ans);
43     }
44     return 0;
45 }

 


 做这道题快有一年了,可是现在看来还是那么的陌生,真不知道自己这一年到底学到了什么?自己是不是在虚度光阴?


这有一个并查集详解,讲得很好

点击打开链接



 

posted @ 2017-08-02 18:22  Veritas_des_Liberty  阅读(272)  评论(0编辑  收藏  举报