[HDU - 1272]小希的迷宫
基础并查集
要注意的点就是成环和空集,成环即Union拥有相同的根的两个点必然就会成环,此时是输出“NO”的。
而空集是要输出“YES”的。
#include <bits/stdc++.h> using namespace std; int ok; int fa[100000 + 10]; int vis[100000 + 10]; int Find(int a) { int r=a; while(fa[r]!=r) r=fa[r]; int i=a; int j; while(i!=r) { j=fa[i]; fa[i]=r; i=j; } return r; } void merge(int a,int b) { int A,B; A=Find(a); B=Find(b); if(A!=B) fa[B]=A; else ok=1; } int main() { int temp1, temp2; while (~scanf("%d %d", &temp1, &temp2)) { if(temp1==0&&temp2==0) { printf("Yes\n"); continue; } if (temp1 + temp2 == -2) break; ok = 0; int a = temp1, b = temp2; for (int i = 1; i <= 100000; i++) { fa[i] = i; vis[i] = 0; } merge(a, b); vis[a] = 1; vis[b] = 1; int flag = 0; while (scanf("%d %d", &a, &b)) { if (!a && !b) break; vis[a] = 1; vis[b] = 1; merge(a,b); } if (ok) { printf("No\n"); continue; } int total = 0; for (int i = 1; i <= 100000; i++) if (vis[i] && fa[i] == i) total++; if (total != 1) printf("No\n"); else printf("Yes\n"); } return 0; }