Find them, Catch them

警方决定捣毁两大犯罪团伙:龙帮和蛇帮,显然一个帮派至少有一人。该城有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

Sample Output

Not sure yet.
In different gangs.
In the same gang.

解题思路:并查集变形,需要两个数组,一个是并查集,另一个存自己的“老大”敌对的”老大“,就是对于两个帮派人,先找到自己的老大,其中一个小弟a找到了自己老大,发现自己老大A里面存的是敌对帮派的老大B,另外一个小弟b就知道了老大B是自己的老大,于是他找到了和自己一起“丢”老大的小老大bb,于是就叫自己的小老大bb去投靠老大B,如此就划分了帮派,然后小b再找老大B,告诉他敌对的帮派老大是A,于是老大B里面敌对的人存的就是A,如果小弟a发现自己的老大A还没有敌对的人(也就是发f那个数组里面存的是自己),就指示老大A敌对的帮派老大是小老大bb,如果小弟b发现老大B里面存的是另外一个人,那么小a就回去告诉老大A咱们帮派的真正老大是谁,然后去投靠(给c【A】赋值)就是一下代码:

void bingchaji(int a,int b)
{
    a=find_father(a);
    b=find_father(b);
    if(f[a]!=a)
    {
        c[f[a]]=b;
    }
    f[a]=b;
    if(f[b]!=b)
    {
        c[f[b]]=a;
    }
    f[b]=a;
}

如果查询的话,就是找两个人的老大,如果老大一样,就是同盟,如果不一样并且其中一方f里面存的是另一方的老大,就是两个帮派,如果老大不一样但是互相存的敌对帮派老大都不是对方的老大,那么就输出不知道

 a=find_father(a);
                b=find_father(b);
                if(a==b)
                    printf("In the same gang.\n");
                else if(f[a]==b||f[b]==a)
                    printf("In different gangs.\n");
                else
                    printf("Not sure yet.\n");

下面是完整代码:

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <stack>
using namespace std;
int c[100009],f[100009];
int find_father(int a)
{
    if(c[a]==a) return a;
    c[a]=find_father(c[a]);
    return c[a];
}
void bingchaji(int a,int b)
{
    a=find_father(a);
    b=find_father(b);
    if(f[a]!=a)
    {
        c[f[a]]=b;
    }
    f[a]=b;
    if(f[b]!=b)
    {
        c[f[b]]=a;
    }
    f[b]=a;
}
int main()
{
    int t,n,m,i,a,b;
    char d;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n,&m);
        getchar();
        for(i=1; i<=n; i++)
        {
            c[i]=i;
            f[i]=i;
        }
        for(i=1; i<=m; i++)
        {
            scanf("%c %d %d",&d,&a,&b);
            getchar();
            if(d=='D')
            {
                bingchaji(a,b);
            }
            else
            {
                a=find_father(a);
                b=find_father(b);
                if(a==b)
                    printf("In the same gang.\n");
                else if(f[a]==b||f[b]==a)
                    printf("In different gangs.\n");
                else
                    printf("Not sure yet.\n");
            }
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值