好早以前做的了,不过最近感觉不错,就贴上来吧 #include<cstdio> #include<cstring> using namespace std; const int MAX = 150000 + 5; int n, m, a, b; char ch; int par[MAX], foe[MAX], rank[MAX]; void inti(){ for(int i = 0; i < MAX; i++){ par[i] = i; foe[i] = 0; rank[i] = 0; } return ; } int find(int a){ if(par[a] == a)return a; else return par[a] = find(par[a]); } void unite(int x, int y){ x = find(x); y = find(y); if(x == y) return ; if(rank[x] < rank[y]){ par[x] = y; } else { par[y] = x; if(rank[x] == rank[y]){ rank[x]++; } } } int same(int x, int y){ return find(x) == find(y); } void solve(){ scanf("%d%d", &n, &m); getchar(); //if(n == 2 && m >= 1){printf("In different gangs.\n");return ;} inti(); for(int i = 0; i < m; i++){ scanf("%c%d%d", &ch, &a, &b); getchar(); if(ch == 'D'){ if(foe[a])unite(foe[a], b); if(foe[b])unite(foe[b], a); foe[b] = a; foe[a] = b; } else { if(same(a, foe[b])) printf("In different gangs.\n"); else if(same(a, b))printf("In the same gang.\n"); else printf("Not sure yet.\n"); } } return ; } int main(){ int t; scanf("%d",&t); getchar(); while(t--){ solve(); } return 0; } </cstring></cstdio>