并查集

#include

int pre[1010]; 

int unionsearch(int root){
    int son, tmp;
    son = root;
    while(root != pre[root]) //寻找根
        root = pre[root];

    while(son != root){ //路径压缩,从son到root路径上的所有节点前驱都设置为root
        tmp = pre[son];
        pre[son] = root;
        son = tmp;
    }
    return root;
}


void join(int root1, int root2){
    int x, y;
    x = unionsearch(root1);
    y = unionsearch(root2);
    if(x != y)
        pre[x] = y; //关联两个节点
}

int main(){
    int num, road, total, i, start, end, root1, root2;
    while(scanf("%d%d", &num, &road) && num){
        total = num - 1; 
        for(i = 1; i <= num; ++i) 
            pre[i] = i;
        while(road--){
            scanf("%d%d", &start, &end); 
            join(start,end);
        }
        printf("%d\n", total);//剩余连通分量
    }
    return 0;
}

https://blog.csdn.net/qq_41593380/article/details/81146850

你可能感兴趣的:(并查集)