POJ 1703 Find them, Catch them(并查集)

本文介绍了一种并查集的拓展应用,通过改进模型解决两个元素间关系未确定的问题。文章详细阐述了如何使用并查集来判断元素是否在同一组,并提供了一个具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分析:并查集的拓展题目。一般的思路是先初始化,各个数自成一个组,然后是两个gangs自成一个组,但由于两个给定元素有三种关系: In the same gang; In different gangs; Not sure yet; 采用此模型的缺点是判断两个元素关系还未确定这种情况比较复杂,故模型需要改进。本题的正确模型是将已经确定关系的元素组成一个集合,然后利用两个元素的根节点是否是同一个来确定这两个元素之间的关系。pre[a]中存放的是a的根结点,relation中存放的是pre[a]与a的关系,0表示两者不在同一个gangs中,1表示两者在同一个gangs中。具体的程序还是沿袭了并查集的init_set()、find()、union()的三步骤。

代码如下:

#include<iostream>
#include<cstdio>

using namespace std;
const int N = 100004;
int t, m, n;
int pre[N];
int relation[N];

void init_set() {
    for (int i = 1; i <= n; ++i) {
        pre[i] = i;
        relation[i] = 1;
    }
}
int find(int a) {
    if (a == pre[a]) {
        return a;
    }
    int temp = find(pre[a]);
    if (!relation[pre[a]]) {
        relation[a] = !relation[a];
    }
    pre[a] = temp;
    return temp;
}
void union_crime(int one, int two) {
    int root1 = find(one);
    int root2 = find(two);
    if (root1 != root2) {
        tr[root2] = root1;
        relation[root2] = (relation[one] + relation[two]) % 2;
    }
}

int main() {
    char op;
    int one, two;
    scanf("%d", &t);
    while (t--) {
        scanf("%d%d", &n, &m);

        init_set();

        for (int i = 0; i < m; ++i) {
            getchar();
            scanf("%c%d%d", &op,&one, &two);
            if (op == 'D') {
                union_crime(one, two);
            }
            else {
                if (find(one) != find(two)) {
                    printf("Not sure yet.\n");
                }
                else if (relation[one] == relation[two]) {
                    printf("In the same gang.\n");
                }
                else {
                    printf("In different gangs.\n");
                }

            }
        }

    }
    return 0;
}       

注意:如果将代码中的scanf和printf改为cin和cout会超时。


参考:poj-1703 Find them, Catch them

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值