一道简单的并查集题目
Sample Input
3
1
a=a
2
b=c
c=d
4
b=a
c=d
d=b
e=f
Sample Output
a
none
a b d
//这个题目没有什么好说的,直接并查集OK,
//之所以写这个题目是为了练一下并查集。
View Code
#include "iostream" using namespace std; #define size 101 int father[size]; char ans[27]; int find(int k) { return father[k]==k?k:father[k]=find(father[k]); } int main() { int T, N, flag; char left, mid, right; cin>>T; while(T--) { cin>>N; for(int i=0; i<27; i++) father[i]=i; flag = 0; for(int i=0; i<N; i++) { cin>>left>>mid>>right; if(left=='a' && right=='a') flag = 1; father[left-'a']=find(right-'a'); } int j=0; for(int i=0; i<27; i++) if(father[i]==0) ans[j++]=i+'a'; if(j==1 && flag) cout<<"a"<<endl; else if(j>1) { for(int i=0; i<j-1; i++) cout<<ans[i]<<" "; cout<<ans[j-1]<<endl; } else cout<<"none"<<endl; } }
posted on 2011-10-22 22:25 More study needed. 阅读(471) 评论(0) 编辑 收藏 举报