POJ - 1703 - Find them, Catch them(带权并查集)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sugarbliss/article/details/89481946

题目链接:https://cn.vjudge.net/problem/POJ-1703

题意:输入n和m,代表有n个人和m个询问,每个询问遵循下面的规则:

  • A a b要求输出a与b是否在同一个帮派或者不能确定。
  • D a b告诉你a和b是不同帮派的成员。

思路:带权并查集,1代表不在同一个帮派0代表在同一个帮派。

#include <stdio.h>
#include <string.h>
using namespace std;
const int N = 1e5 + 7;
int f[N], w[N], n, m, flag;
void init()
{
    for(int i = 0; i <= n; i++)
        f[i] = i, w[i] = 0;
}
int findd(int x)
{
    if(f[x] == x) return x;
    int t = f[x];
    f[x] = findd(f[x]);
    w[x] = (w[x] + w[t]) % 2;
    return f[x];
}
void unint(int x, int y)
{
    int tx = findd(x);
    int ty = findd(y);
    if(tx != ty)
    {
        f[tx] = ty;
        w[tx] = (-w[x] + w[y] + 1 + 2) % 2;
    }
}
int main()
{
    int t, cas = 1; scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n, &m);
        init();
        flag = 0;
        while(m--)
        {
            int a, b; char str[2];
            scanf("%s %d %d", str, &a, &b);
            if(str[0] == 'D') unint(a, b);
            else
            {
                if(findd(a) == findd(b))
                {
                    if((w[a] - w[b] + 2) % 2 == 0)
                        puts("In the same gang.");
                    else puts("In different gangs.");
                }
                else puts("Not sure yet.");
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sugarbliss/article/details/89481946