【HDOJ】1272 小希的迷宫
并查集。
1 #include <stdio.h> 2 #include <string.h> 3 4 #define MAXNUM 100001 5 6 int bin[MAXNUM]; 7 8 int find(int x) { 9 int r = x; 10 11 while (r != bin[r]) 12 r = bin[r]; 13 14 return r; 15 } 16 17 int merge(int x, int y) { 18 int fx, fy; 19 20 fx = find(x); 21 fy = find(y); 22 23 if (fx == fy) 24 return -1; 25 else 26 bin[fx] = fy; 27 28 return 0; 29 } 30 31 int main() { 32 int x, y; 33 int i, flg = 0, cnt, tmp; 34 35 while (scanf("%d %d", &x, &y) != EOF) { 36 if (x==-1 && y==-1) 37 break; 38 if (x==0 && y==0) { 39 cnt = 0; 40 for (i=1; cnt<=1&&i<MAXNUM; ++i) 41 if (bin[i] == i) 42 ++cnt; 43 if (cnt>1 || flg) 44 printf("No\n"); 45 else 46 printf("Yes\n"); 47 flg = 0; 48 memset(bin, 0, sizeof(bin)); 49 } else { 50 if ( bin[x] == 0 ) 51 bin[x] = x; 52 if ( bin[y] == 0) 53 bin[y] = y; 54 tmp = merge(x, y); 55 if ( !flg ) flg = tmp; 56 } 57 } 58 59 return 0; 60 }