- #include<iostream>
- #include<cstdio>
- using namespace std;
- const int maxn=30;
- int t=0,temp,parent[maxn];
- bool visited[maxn];
- void initial(){
- for(int i=0;i<=maxn;i++)parent[i]=i;
- for(int i=0;i<=maxn;i++)visited[i]=false;
- }
- int getRoot(int k){
- if(k!=parent[k]) parent[k]=getRoot(parent[k]);
- return parent[k];
- }
- void Union(int a,int b){parent[a]=b;}
- void solve(){
- char ch[3];
- gets(ch);
- temp=ch[0]-'A'+1;
- while(gets(ch)){
- if(!ch[0]) break;//判断是否是空行
- int p=getRoot(ch[0]-'A'+1),q=getRoot(ch[1]-'A'+1);
- if(p!=q) Union(p,q);
- }
- }
- void output(){
- int cnt=0;
- for(int i=1;i<=temp;i++){
- if(!visited[getRoot(i)]){
- cnt++;
- visited[getRoot(i)]=true;
- }
- }
- printf("%d\n",cnt);
- if(t) printf("\n");
- }
- int main(){
- while(cin>>t){//原来大的测试也是多组的
- getchar();
- getchar();
- while(t--){
- initial();
- solve();
- output();
- }
- }
- return 0;
- }
uva 459 并查集
最新推荐文章于 2023-03-09 21:25:32 发布