版权声明:转载请注明出处。 https://blog.csdn.net/u014427196/article/details/40261019

并查集:种类并查集:

分为1~N,N~2N两类;

a,b第一次出现时是p[a]=a,p[b]=b;

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

int p[200010];

int findd(int x)
{
    if (p[x] < 0 )
        return x;
    else
        return p[x] = findd(p[x]);
}

int main ()
{
    int t;
    scanf ("%d",&t);
    while (t--)
    {
        int n,m;
        char b[5];
        int c,d;
        scanf ("%d%d",&n,&m);
        memset(p,-1,sizeof(p));

        for (int i=1;i<=m;i++)
        {
            scanf ("%s",b);
            scanf ("%d %d",&c,&d);
            if (!strcmp(b,"A"))
            {
                if (n==2)
                    printf("In different gangs.\n");
                else if (findd(c) != findd(d) && findd(c)!=findd(d+n))
                    printf("Not sure yet.\n");
                else if (findd (c) == findd(d))
                    printf("In the same gang.\n");
                else
                    printf("In different gangs.\n");
            }
            else
            {
                if (findd (c)!= findd (d+n))
                {
                    p[findd (c)] = findd (d+n);
                    p[findd (d)] = findd (c+n);
                }
            }
        }
    }
    return 0;
}