数据结构1 - 05-树8 File Transfer

 

 

 1 #include<stdio.h>
 2 #define MAXN 10001
 3 int a[MAXN],root[MAXN];
 4 int getfather(int x);
 5 int main(){
 6     int i,a1,a2,fa1,fa2,ch;
 7     char op;
 8     scanf("%d",&a[0]);
 9     for(i=1;i<=a[0];i++){
10         root[i] = 0;
11         a[i] = i;
12     }
13     getchar();
14     scanf("%c",&op);
15     while(op!='S'){
16         scanf("%d %d",&a1,&a2);
17          fa1 = getfather(a1);
18          fa2 = getfather(a2);
19         if(op=='C'){  //check
20            if(fa1!=fa2) printf("no\n");
21            else printf("yes\n");
22         }
23         else if(op=='I'){ //input
24            if(fa1!=fa2){
25                //not connect
26                a[fa1] = fa2;
27                getfather(a1);
28                getfather(a2);
29            }
30         }
31          getchar();
32          scanf("%c",&op);
33 
34 
35     }
36     int s=0;
37     for(i=1;i<=a[0];i++){
38         if(a[i]==i) root[i]=1;
39     }
40     for(i=1;i<=a[0];i++) s+=root[i];
41     if(s==1) printf("The network is connected.\n");
42     else printf("There are %d components.\n",s);
43 
44     return 0;
45 }
46 int getfather(int x){
47     int fa,pre;
48     fa = x;
49     while(fa!=a[fa]){
50         fa = a[fa];
51     }
52     while(x!=a[x]){
53         pre = a[x];
54         a[x] = fa;
55         x = pre;
56     }
57     return fa;
58 }
59     
View Code

总结:并查集是一种维护集合的数据结构。

猜你喜欢

转载自www.cnblogs.com/Learn-Excel/p/12631581.html