思路:
关系型并查集。简化的食物链。
实现:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 5 const int MAXN = 100000; 6 7 int a[MAXN + 10]; 8 int par[2 * MAXN + 10]; 9 int ran[2 * MAXN + 10]; 10 int t, n, m, x, y; 11 char p; 12 13 void init(int n) 14 { 15 for (int i = 0; i <= n; i++) 16 { 17 par[i] = i; 18 ran[i] = 0; 19 } 20 } 21 22 int find(int x) 23 { 24 if (x == par[x]) 25 return x; 26 return par[x] = find(par[x]); 27 } 28 29 void unite(int x, int y) 30 { 31 x = find(x); 32 y = find(y); 33 if (x == y) 34 { 35 return; 36 } 37 if (ran[x] < ran[y]) 38 { 39 par[x] = y; 40 } 41 else 42 { 43 par[y] = x; 44 if (ran[x] == ran[y]) 45 { 46 ran[x] ++; 47 } 48 } 49 } 50 51 bool same(int x, int y) 52 { 53 return find(x) == find(y); 54 } 55 56 int main() 57 { 58 cin >> t; 59 while (t--) 60 { 61 cin >> n >> m; 62 getchar(); 63 init(2 * n); 64 for (int i = 0; i < m; i++) 65 { 66 scanf("%c %d %d", &p, &x, &y); 67 getchar(); 68 x--; 69 y--; 70 if (p == 'D') 71 { 72 unite(x, y + n); 73 unite(x + n, y); 74 } 75 else 76 { 77 if (same(x, y) || same(x + n, y + n)) 78 { 79 puts("In the same gang."); 80 } 81 else if (same(x + n, y) || same(x, y + n)) 82 { 83 puts("In different gangs."); 84 } 85 else 86 { 87 puts("Not sure yet."); 88 } 89 } 90 } 91 } 92 return 0; 93 }