裸的并查集,注意两个地方:
1. 最后所有的点要在同一个集合中
2. 输入只有0 0时需要特殊处理
code:
#include<cstdio> #include<cstring> int p[ 100001] ; bool vis[ 100001] ; void make_set(){ for( int i= 1; i<= 100001; i++) p[i] = i ; } int find_set( int x){ if(p[x]!=x) p[x] = find_set(p[x]) ; return p[x] ; } void union_set( int x, int y){ x = find_set(x) ; y = find_set(y) ; p[x] = y ; } int main(){ int x, y, flag, node, edge ; while(~scanf( " %d%d ", &x, &y)&&x+y+ 2){ flag = 0 ; node = 2, edge = 1 ; if(!(x+y)){ printf( " Yes\n ") ; continue ; } memset(vis, false, sizeof(vis)) ; vis[x] = true, vis[y] = true ; make_set() ; union_set(x, y) ; while(~scanf( " %d%d ", &x, &y)&&x+y){ edge ++ ; if(!vis[x]) node ++ ; if(!vis[y]) node ++ ; vis[x] = vis[y] = true ; if(flag||find_set(x)==find_set(y)){ flag = 1 ; continue ; } union_set(x, y) ; } if(!flag&&(node-edge== 1)) printf( " Yes\n ") ; else printf( " No\n ") ; } return 0 ;}