题目大意:一共有两个类,两种操作D X Y表示X Y在不同的类里面,A X Y 询问X Y之间的关系(未知,相同,不同)
分析:简单带权并查集,D[i]表示与i对立的类,维护好这个变量就可以了。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <set> 5 #include <algorithm> 6 #include <map> 7 #include <queue> 8 #include<vector> 9 #define maxn 100010 10 #define maxm 100010 11 #define mod 1000000000000000000 12 #define INF 0x3fffffff 13 using namespace std; 14 int father[maxn]; 15 int n; 16 int d[maxn]; 17 void init(){ 18 for(int i=0;i<=n;++i){ 19 father[i]=i; 20 d[i]=-1; 21 } 22 } 23 int Find(int x){ 24 return father[x]==x?x:father[x]=Find(father[x]); 25 } 26 void Union(int x,int y){ 27 x =Find(x); 28 y =Find(y); 29 if(x!=y)father[x]=y; 30 } 31 int main () 32 { 33 int t,m; 34 scanf("%d",&t); 35 while(t--){ 36 scanf("%d%d",&n,&m); 37 init(); 38 char ch[10]; 39 int x,y; 40 for(int i=0;i<m;++i){ 41 scanf("%s%d%d",ch,&x,&y); 42 int fx = Find(x); 43 int fy = Find(y); 44 if(ch[0]=='A'){ 45 if(fx==fy)printf("In the same gang. "); 46 else if(fx == Find(d[y]))printf("In different gangs. "); 47 else printf("Not sure yet. "); 48 } 49 else { 50 if(d[x]==-1){ 51 d[x]=fy; 52 } 53 if(d[y]==-1){ 54 d[y]=fx; 55 } 56 Union(x,d[fy]); 57 Union(y,d[fx]); 58 } 59 } 60 } 61 }