poj1611 The Suspects 并查集_小优化

poj1611 The Suspects 并查集_小优化

标签:并查集

题目链接
原文出处
并查集基础
(1)

/*
    可以通过压缩路径来优化,在查找到祖先节点之后,
    将路径上所有它的子孙节点都直接连接到它上面,这样树的高度就大大降低了。
*/
#include <stdio.h>

int num[30005];  //结点所在集合元素的个数
int father[30005];

void make_set(int x){  初始化集合
    father[x] = -1;
    num[x] = 1;
}

int find_set(int x){  查找x元素所在集合
    int r = x, temp;

    while(father[r] != -1)  r = father[r];  //找到根节点
    while(x != r){  //压缩路径,将路径上r所有的子孙都直接连接到r上
        temp = father[x];
        father[x] = r;
        x = temp;
    }
    return  x;
}

void union_(int x, int y){  //合并x, y所在的集合
    x = find_set(x), y = find_set(y);
    if(x == y)  return ;  //同一个集合则不需要合并
    if(num[x] < num[y]) {  //小集合合并到大集合
        father[x] = y;
        num[y] += num[x];
    }
    else{
        father[y] = x;
        num[x] += num[y];
    }
}

int main(){
    int n, m, t, x, y, i, j;

    while(scanf("%d %d", &n, &m) && (n || m)){
        for(i = 0; i < n; i++)  make_set(i);
        for(i = 0; i < m; i++){
            scanf("%d", &t);
            scanf("%d", &x);
            for(j = 1; j < t; j++){
                scanf("%d", &y);
                union_(x, y);
            }
        }
        printf("%d\n", num[find_set(0)]);
    }

    return 0;
}

(2)

/*
    对于根节点来说,father[]本身就可以记录节点数目,只不过值是负的。
*/
#include <stdio.h>

int father[30005];

void make_set(int x){  //初始化集合
    father[x] = -1;
}

int find_set(int x){  //查找x元素所在集合
    int r = x, temp;

    while(father[r] > 0)  r = father[r];  找到根节点
    while(x != r){  //压缩路径,将路径上r所有的子孙都直接连接到r上
        temp = father[x];
        father[x] = r;
        x = temp;
    }
    return  x;
}

void union_(int x, int y){  //合并x, y所在的集合
    x = find_set(x), y = find_set(y);
    if(x == y)  return ;  //同一个集合则不需要合并
    if(father[x] < father[y]) {  小集合合并到大集合(负数比较), <
        father[x] += father[y];
        father[y] = x;
        }
    else{
        father[y] += father[x];
        father[x] = y;
        }
}

int main(){
    int n, m, t, x, y, i, j;

    while(scanf("%d %d", &n, &m) && (n || m)){
        for(i = 0; i < n; i++)  make_set(i);
        for(i = 0; i < m; i++){
            scanf("%d", &t);
            scanf("%d", &x);
            for(j = 1; j < t; j++){
                scanf("%d", &y);
                union_(x, y);
            }
        }
        printf("%d\n", -father[find_set(0)]);  //结点数目为负值
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值