二叉树—并查集
注意:下标必须是人物编号,且从1—INF
1.核心代码:
#include<iostream> using namespace std; const int maxn=1000; class Ufstree { struct node { int data; int rank; int par;//parent }; node t[maxn]; int len; public : void make_set(int n) { len=n; for(int i=1;i<=n;i++) { t[i].par=i; t[i].rank=0; } } int find_set(int x) { return x==t[x].par ? x:find_set(t[x].par); } void mixed(int x,int y) { int fx=find_set(x); int fy=find_set(y); if(t[fx].rank>t[fy].rank) t[fy].par=fx; else { t[fx].par=fy; if(t[fx].rank==t[fy].rank) t[fy].rank++; } } int find_num()//集合的个数 { int num=0; for(int i=1;i<=len;i++) if(t[i].par==i) num++; return num; } };
2.完整代码加例题:
#include<iostream> using namespace std; const int maxn=1000; class Ufstree { struct node { int data; int rank; int par;//parent }; node t[maxn]; int len; public : void make_set(int n) { len=n; for(int i=1;i<=n;i++) { t[i].par=i; t[i].rank=0; } } int find_set(int x) { return x==t[x].par ? x:find_set(t[x].par); } void mixed(int x,int y) { int fx=find_set(x); int fy=find_set(y); if(t[fx].rank>t[fy].rank) t[fy].par=fx; else { t[fx].par=fy; if(t[fx].rank==t[fy].rank) t[fy].rank++; } } int find_num()//集合的个数 { int num=0; for(int i=1;i<=len;i++) if(t[i].par==i) num++; return num; } }; int main() { int n,m; Ufstree t; while(cin>>n>>m) { if(n==0&&m==0) break; bool flag=true; t.make_set(n); while(m--) { int a,b; cin>>a>>b; int fa=t.find_set(a); int fb=t.find_set(b); if(fa==fb) flag=false; else t.mixed(fa,fb); } if(flag&&t.find_num()==1) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
例题地址:http://tk.hustoj.com/status.php?user_id=shenyu