https://vjudge.net/problem/POJ-1703
9ms多,卡着时间过了。上次一道并查集也是这样,总觉得要学一波并查集的优化。。
续:好像是可以只做一层存放敌人即可。
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<stack> 8 #define lson l, m, rt<<1 9 #define rson m+1, r, rt<<1|1 10 #define INF 0x3f3f3f3f 11 typedef unsigned long long ll; 12 using namespace std; 13 const int N=100000; 14 int t, n, m, x, y, pre[200010]; 15 char c; 16 int find(int x) 17 { 18 while(x != pre[x]){ 19 x = pre[x]; 20 } 21 return x; 22 } 23 int is_same(int a, int b) 24 { 25 int tx = find(a); 26 pre[a] = tx; 27 int ty = find(b); 28 pre[b] = ty; 29 if(tx == ty) return 1; 30 return 0; 31 } 32 void join(int a, int b) 33 { 34 int tx = find(a); 35 pre[a] = tx; 36 int ty = find(b); 37 pre[b] = ty; 38 pre[tx] = ty; 39 } 40 int main() 41 { 42 scanf("%d", &t); 43 while(t--){ 44 scanf("%d%d", &n, &m); 45 for(int i = 1; i <= N*2; i++){ 46 pre[i] = i; 47 } 48 //c = getchar(); 49 for(int i = 0; i < m; i++){ 50 c = getchar(); 51 scanf("%c%d%d", &c, &x, &y); 52 if(c == ‘A‘){ 53 if(is_same(x, y)||is_same(x+N, y+N)){ 54 printf("In the same gang.\n"); 55 } 56 else{ 57 if(!is_same(x, y)&&!is_same(x, y+N)){ 58 printf("Not sure yet.\n"); 59 } 60 else printf("In different gangs.\n"); 61 } 62 } 63 else{ 64 join(x, y+N); 65 join(x+N, y); 66 } 67 } 68 } 69 return 0; 70 }
poj1703 Find them, Catch them(并查集)
原文:https://www.cnblogs.com/Surprisezang/p/8996856.html