并查集简单题

The Suspects

题目传送:POJ-1611-The Suspects

AC代码:

#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;

int n, m;
const int maxn = 30005;
int pa[maxn];
int tot[maxn];//记录当前集合的总数 

int find(int x) {
    return pa[x] == x ? x : pa[x] = find(pa[x]);//带路径压缩 
}

void link(int x, int y) {
    int px = find(x);
    int py = find(y);
    if(px == py) return;
    pa[px] = py;
    tot[py] += tot[px];
}

int main() {
    while(scanf("%d %d", &n, &m) != EOF) {
        if(n == 0 && m == 0) break;

        for(int i = 0; i <= n; i ++) {
            pa[i] = i;
            tot[i] = 1;
        }

        int k, h, s;
        for(int i = 0; i < m; i ++) {
            scanf("%d", &k);
            scanf("%d", &h);
            for(int j = 1; j < k; j ++) {
                scanf("%d", &s);
                link(h, s);
            }
        }

        printf("%d\n", tot[find(0)]);
    }
    return 0;
}



Cube Stacking

题目传送:POJ - 1988 - Cube Stacking

AC代码:

#include <map>
#include <set>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;

const int maxn = 30005;
int pa[maxn];
int under[maxn];
int sum[maxn];

int p;

int find(int x) {
    if(x == pa[x]) {
        return x;
    }
    int t = find(pa[x]);
    under[x] += under[pa[x]];//路径压缩的时候要更新under数组,且这个数组只能放这里,因为要先更新祖先 
    pa[x] = t;
    return pa[x];
}

void link(int x, int y) {//把x所在的堆放到y所在的堆上 
    int px = find(x);
    int py = find(y);
    if(px == py) {
        return;
    }
    pa[px] = py;
    under[px] = sum[py];//将下面那个堆的总数更新到上面那个堆的根 
    sum[py] += sum[px];//计算现在这个堆的总数,不能和上面那个位置互换 
}

int main() {
    while(scanf("%d", &p) != EOF) {

        for(int i = 0; i < maxn; i ++) {
            pa[i] = i;
            under[i] = 0;
            sum[i] = 1;
        }

        char op[15];
        int a, b;
        for(int i = 0; i < p; i ++) {
            scanf("%s", op);
            if(op[0] == 'M') {
                scanf("%d %d", &a, &b);
                link(a, b);
            }
            else {
                scanf("%d", &a);
                find(a);
                printf("%d\n", under[a]);
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值