POJ 1703 Find them, Catch them 种类并查集

输入n,m表示一共有n个节点 ,m个行条件+询问
A表示询问A与B是不是同类
D表示 A与B不是同类
我们用两个节点rank值的和值来表示是否为同类
和值%2==0表示为同类

和值%2==1表示为不同类

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 500000+5
int fa[N],rank[N];
void init(int n){//初始化
    for(int i=0; i<=n; i++){
        fa[i]=i;
        rank[i]=0;
    }
}
int find(int x)//找父节点
{
    if(x==fa[x])    return x;
    else
    {
        int f=fa[x];
        fa[x]=find(fa[x]);//递归
        rank[x]=(rank[x]+rank[f])%2;//更新rank值
        return fa[x];
    }
}
void merge(int x,int y)
{
    int fx=find(x),fy=find(y);
    if(fx==fy)  return ;//
    else
    {
        fa[fy]=fx;  //更新fa
        rank[fy]=(rank[x]-rank[y]+2+1)%2;
    }
}
int main()
{
 //   freopen("in.txt","r",stdin);
    int n,m,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        init(n);
        int ans=0;
        for(int i=0; i<m; i++)
        {
            int b,c;
            char a;
            getchar();
            scanf("%c%d%d",&a,&b,&c);
            if(a=='D')
                merge(b,c);
            else
            {
                int x=find(b),y=find(c);
                if(y!=x)//没有相同的父节点表示先前没有联系
                    printf("Not sure yet.\n");
                else if(rank[b]==rank[c]&&x==y)//父节点相同 并且rank值%2==0(0 +0或者1+1)
                    printf("In the same gang.\n");
                else printf("In different gangs.\n");
            }
        }
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值