POJ 1703 Find them, Catch them

原文转自:http://blog.csdn.net/yang_7_46/article/details/8554043
并查集应用。

这个题目和【食物链】类似。

a[x] = 0  表示x与父节点同gang
 a[x] = 1 表示与父节点不同gang
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 100005;
int set[MAXN], a[MAXN];

int Find_set(int x) {
    if (x == set[x]) return x;
    int t = Find_set(set[x]);
    a[x] = (a[set[x]] + a[x]) % 2;
    return set[x] = t;
}
void Union(int x, int y) {
    int fx = Find_set(x);
    int fy = Find_set(y);
    set[fx] = fy;
    if (a[y] == 0)
        a[fx] = 1 - a[x];
    else a[fx] = a[x];
}
int main() {
    int t, n, m, fx, fy, x, y;
    char ch;

    scanf("%d", &t);
    while ( t-- ) {
        scanf("%d %d", &n, &m);
        for (int i=1; i<=n; i++) {
            set[i] = i;
            a[i] = 0;
        }
        while ( m-- ) {
            scanf(" %c %d %d", &ch, &x, &y);
            if (ch == 'A') {
                fx = Find_set(x);
                fy = Find_set(y);
                if (fx != fy)
                    printf("Not sure yet.\n");
                else if (a[x] == a[y])
                    printf("In the same gang.\n");
                else printf("In different gangs.\n");
            } else Union(x, y);
        }
    }
    return 0;
}

关于WA,这里还是漏掉了只有两个人的情况,所以无法AC
本来是用DFS去染色的,结果一直超时,一直想有没有别的办法,使得让两个不连通的图在连通的那一刻,使得图中的所有元素的颜色完成转换,如(8,4),假设8,4都是默认在两个图中为阵营1的话,那么这组测是数据出现的时候,其中一个图的颜色必须要重染,但是,最终是没有想到一个很好的办法,看到这个代码之后,发现原来可以不用重染另一个图中的所有元素,只需要重染一个就好了,其中也充分的利用了并查集的路径压缩和递归

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值