标签:并查集
#include <cstdio> #include <iostream> #include <queue> #include <set> using namespace std; struct node{ int x,y; }; int fa[100015]; int find(int x){ while(fa[x]!=x){ x = fa[x]; } return x; } int d[100015]; node b[100015]; int unit(int x,int y){ if(d[x] < d[y]){ fa[x] = y; } else if(d[y] < d[x]){ fa[y] = x; } else{ fa[x] = y; d[x] ++; } } int main(){ node a; while(scanf("%d%d",&a.x,&a.y)){ if(a.x == -1&& a.y ==-1)break; int ma = 0; int cc = 0; b[cc] = a; while(b[cc].x || b[cc].y){ cc++; scanf("%d%d",&b[cc].x,&b[cc].y); ma = max(ma,max(b[cc].x,b[cc].y)); } for(int i = 0;i <= ma+1;i++){ fa[i] = i; d[i] = 1; } int flag = 1; int j = 0; while(j < cc){ a = b[j]; int fx = find(a.x); int fy = find(a.y); if(fx == fy){ flag = 0; break; } else{ unit(fx,fy); } j++; } if(flag){ set<int> se; for(int i = 0;i < cc && se.size() <= 1;i++){ se.insert(find(b[i].x)); se.insert(find(b[i].y)); } if(se.size() <= 1){ cout << "Yes" << endl; } else{ cout << "No" << endl; } } else{ cout << "No" << endl; } } return 0; }
标签:并查集
原文地址:http://blog.csdn.net/qq_24667639/article/details/45794435