#include <iostream> #include <vector> using namespace std; class Union_Find_Sets { public: inline Union_Find_Sets() {} void make_set(int n); int find_set(int n); void union_set(int x,int y); int count_set(); private: vector<int> _father; vector<int> _rank; int _set_size; }; void Union_Find_Sets::make_set(int n) { _father.clear(); _rank.clear(); _set_size=n; for(int cnt=0;cnt<=n;++cnt) { _father.push_back(cnt); _rank.push_back(1); } } int Union_Find_Sets::find_set(int n) { if(n!=_father[n]) { _father[n]=find_set(_father[n]); } return _father[n]; } void Union_Find_Sets::union_set(int x,int y) { int x_set=find_set(x);//同时完成了压缩路径与查找x所属集合的根结点序号x_set int y_set=find_set(y);//同时完成了压缩路径与查找y所属集合的根结点序号y_set if(x_set==y_set)//如果x,y属于同一集合,无需合并 { return; } if(_rank[x_set]<_rank[y_set])//根据集合的大小,将小集合合并到大集合的根结点之下 { _rank[y_set]+=_rank[x_set]; _father[x_set]=y_set; } else { _rank[x_set]=_rank[y_set]; _father[y_set]=x_set; } } int Union_Find_Sets::count_set() { int set_count=0; for(int cnt=1;cnt<=_set_size;++cnt) { if(cnt==find_set(cnt)) { ++set_count; } } return set_count; } int main() { int first,second; bool flag=false; Union_Find_Sets maze; maze.make_set(100001); while(true) { while(cin>>first>>second&&first!=0&&second!=0&&first!=-1&&second!=-1) { if(maze.find_set(first)==maze.find_set(second)) { flag=true;//出现环路 continue; } maze.union_set(first,second);//否则合并 } if(flag==false) { cout<<"Yes"<<endl; } else { cout<<"No"<<endl; } flag=false; maze.make_set(100001); } } 题目:http://acm.hdu.edu.cn/showproblem.php?pid=1272