题目似乎并没有什么特别的…类似那道经典的食物链或者关押罪犯,利用并查集的补集去做就好了;唯一要注意的就是本题卡cin,换成scanf和getchar就能过;
利用cin的懒人写法
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int par[200050];
int find(int x)
{
return par[x]==x?x:par[x]=find(par[x]);
}
bool unite(int x,int y)
{
x=find(x),y=find(y);
if(x==y)return false;
par[x]=y;return true;
}
int main()
{
int t,n,m,i,j,k;
cin>>t;
while(t--){
cin>>n>>m;for(i=1;i<=2*n;i++)par[i]=i;
string str;int p,q;
for(i=1;i<=m;i++){
cin>>str>>p>>q;
if(str=="D"){
unite(p,q+n);unite(p+n,q);
}
else{
if(find(p)==find(q)||find(p+n)==find(q+n))cout<<"In the same gang."<<endl;//这里写成&&也行,下面也是一样,无关大雅
else if(find(p)==find(q+n)||find(q)==find(p+n))cout<<"In different gangs."<<endl;
else cout<<"Not sure yet."<<endl;
}
}
}
return 0;
}
改成scanf以后:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int par[200050];
int find(int x)
{
return par[x]==x?x:par[x]=find(par[x]);
}
bool unite(int x,int y)
{
x=find(x),y=find(y);
if(x==y)return false;
par[x]=y;return true;
}
int main()
{
int t,n,m,i,j,k;
cin>>t;
while(t--){
cin>>n>>m;for(i=1;i<=2*n;i++)par[i]=i;
char c;int p,q;getchar();
for(i=1;i<=m;i++){
c=getchar();scanf("%d%d",&p,&q);getchar();
if(c=='D'){
unite(p,q+n);unite(p+n,q);
}
else{
if(find(p)==find(q)||find(p+n)==find(q+n))cout<<"In the same gang."<<endl;
else if(find(p)==find(q+n)||find(q)==find(p+n))cout<<"In different gangs."<<endl;
else cout<<"Not sure yet."<<endl;
}
}
}
return 0;
}