每次给的关系表示两个物品不属于同一集合,题目关键在于一共只有两个集合,那就设一个对立关键字好了,表示两个物品对立,每次给一个对立关系u,v,就把(u和v的对立)与(v和u的对立)并起来,最后査就好了。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<stack>
#include<cstring>
#include<map>
#include<string>
#include<climits>
#define maxn 110000
using namespace std;
int father[maxn];
int opp[maxn];
int _find(int x)
{
int t=x;
while(x!=father[x])
x=father[x];
while(t!=father[t])
{
int temp=t;
t=father[t];
father[temp]=x;
}
return x;
}
bool join(int x,int y)
{
x=_find(x);
y=_find(y);
if(x!=y)
{
father[x]=y;
return true;
}
return false;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=0;i<=n;++i)
{
father[i]=i;
opp[i]=-1;
}
for(int i=0;i<m;++i)
{
char op[10];
int u,v;
scanf("%s%d%d",op,&u,&v);
if(op[0]=='D')
{
if(opp[u]==opp[v] && opp[u]==-1)
{
opp[u]=v;
opp[v]=u;
}
else if(opp[u]==-1)
{
opp[u]=v;
join(u,opp[v]);
}
else if(opp[v]==-1)
{
opp[v]=u;
join(v,opp[u]);
}
else
{
join(u,opp[v]);
join(v,opp[u]);
}
}
else
{
if(_find(u)== _find(v))
printf("In the same gang.\n");
else if(_find(u)==_find(opp[v]))
printf("In different gangs.\n");
else
printf("Not sure yet.\n");
}
}
}
}