并查集模板练手。
递归版本
#include<bits/stdc++.h> using namespace std; const int N=1e4+5; int father[N]; int find(int mid){ if (father[mid]!=mid){ father[mid]=find(father[mid]); } return father[mid]; } void union_fa(int x,int y){ father[find(x)]=find(y); } int main(){ int n,m; cin>>n>>m; for (int i=1;i<=n;i++) father[i]=i; for (int i=1;i<=m;i++){ int z,x,y; cin>>z>>x>>y; if (z==2) if (find(x)==find(y)) cout<<"Y\n"; else cout<<"N\n"; else { union_fa(x,y); } } return 0; }
非递归版本
#include<bits/stdc++.h> using namespace std; const int N=1e4+5; int father[N],size[N],Stack[N]; int find(int mid){ int start=0; while (father[mid]!=mid){ Stack[start++]=mid; mid=father[mid]; } for (int i=0;i<start;i++) Stack[i]=mid; return father[mid]; } void union_fa(int x,int y){ father[find(x)]=find(y); } int main(){ int n,m; cin>>n>>m; for (int i=1;i<=n;i++){ father[i]=i; size[i]=1; } for (int i=1;i<=m;i++){ int z,x,y; cin>>z>>x>>y; if (z==2) if (find(x)==find(y)) cout<<"Y\n"; else cout<<"N\n"; else { if (size[find(x)]<size[find(y)]){ union_fa(x,y); size[find(y)]+=size[find(x)]; } else{ union_fa(y,x); size[find(x)]+=size[find(y)]; } } } return 0; }
标签:int,查集,father,mid,P3367,find,模板 From: https://www.cnblogs.com/purple123/p/18014775