poj1703(种类并查集)

题目链接:http://poj.org/problem?id=1703

题目:
警方决定捣毁两大犯罪团伙:龙帮和蛇帮,显然一个帮派至少有一人。该城有N个罪犯,编号从1至N(N<=100000。将有M(M<=100000)次操作。
D a b 表示a、b是不同帮派
A a b 询问a、b关系
Input
多组数据。第一行是数据总数 T (1 <= T <= 20)每组数据第一行是N、M,接下来M行是操作
Output
对于每一个A操作,回答”In the same gang.”或”In different gangs.” 或”Not sure yet.”
Sample Input
1
5 5
A 1 2
D 1 2
A 1 2
D 2 4
A 1 4

思路见代码:

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

using namespace std;

const int maxn = 100000+5;

int fa[2*maxn],height[maxn*2];//height数组用来控制并查的方向
int T,N,M,a,b;
char c;

void init()//初始化
{
    for(int i=1; i<=2*N; i++)
    {
        fa[i]=i;
        height[i]=0;
    }
}

int find_(int x)//并查集
{
    return x==fa[x]? x : fa[x]=find_(fa[x]);
}

void unit (int u, int v)
{
    int x,y;
    x=find_(u);
    y=find_(v);
    if(x==y)
    return;
    if(height[y]>height[x])
        fa[x]=y;
    else
    {
        fa[y]=x;
        if(height[x]==height[y])
            height[x]++;
    }
}

bool same(int u, int v)
{
    return find_(u)==find_(v);
}

int main()
{
    scanf("%d",&T);

    while(T--)
    {
        flag=0;
        scanf("%d %d",&N,&M);
        init();
        for(int i=0; i<M; i++)
        {
            getchar();
            scanf("%c %d %d",&c,&a,&b);
            if(c=='D')
            {
                unit(a,b+N);// b和b+N不在同一个帮派,则把a和b+N看作一个帮派的,合并得到一起
                unit(a+N,b);// 同理由上可得
            }
            else
            {
                if(same(a,b))
                    printf("In the same gang.\n");
                else if(same(a,b+N))
                    printf("In different gangs.\n");
                else
                    printf("Not sure yet.\n");
            }

        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36300700/article/details/80070020