MOOC Zhejiang University Data Structure-05-Tree 8 File Transfer (25 points)

Forgot to refer to which blog, and check the collection, the array subscript represents the stored value, the array element represents the subscript of its parent node, the element value of the root node is negative, and its absolute value is the number of nodes contained

#include<stdio.h>
int s[10005];//forget the ";"
// int find(int x){
    
    
//     for(;s[x]>0;x=s[x]);
//     return x;
// }

int find(int x){
    
    //查找根节点下标
	if(s[x] < 0)
		return x;
	else
		return s[x] = find( s[x] );   //先改变树的结构,再返回根结点
}

// void union(int a,int b){
    
    
//     int root1 = find(a);
//     int root2 = find(b);
//     s[root1] = root2;
// }

void Union(int a, int b) {
    
    //union是关键字 因此这个函数名需要大写 不然会报错
//将a,b两个电脑连在一起,将小集合的树连在大集合的树上
	int faA = find(a);
	int faB = find(b);
	if(s[faA] > s[faB])
		s[faA] = faB;
	else {
    
    
		if(s[faA] == s[faB])
			s[faA]--;
		s[faB] = faA;
	}
}
void Initiate(int n){
    
    
    for(int i=1;i<=n;++i){
    
    
        s[i] = -1;
    }
}
void Input(){
    
    
    int a,b;
    scanf("%d %d",&a,&b);
    Union(a,b);
}
void Check(){
    
    
    int a,b;
    scanf("%d %d",&a,&b);
    int ra = find(a);
    int rb = find(b);
    if(ra == rb){
    
    
        printf("yes\n");
    }
    else{
    
    
    printf("no\n");
    }
}
void Ouput(int n){
    
    
    int cou = 0;
    for(int i=1;i<=n;++i){
    
    
        if (s[i]<0){
    
    
            cou++;
        }
    }
    if(cou == 1){
    
    
        printf("The network is connected.");
    }
    else{
    
    
        printf("There are %d components.",cou);
    }
    
}
int main(){
    
    
    int n;
    char in;
    scanf("%d",&n);
    Initiate(n);
    do{
    
    
        scanf("%c",&in);
        switch(in){
    
    
        case 'I':Input();break;
        case 'C':Check();break;
        case 'S':Ouput(n);break;
        }
    }while(in!='S');
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43919570/article/details/105554105