D. Secret Passwords.Codeforces Round #603 (Div. 2)

http://codeforces.com/contest/1263/problem/D

题目大意

给你一堆密码,如果密码里面有共同字母,那么他们就被建立一个等价关系,并且等价关系之间具有传递性。问你共有多少个密码体系。即多少组密码(如果两个密码有关系就会被分到同一组)

做法

考虑用并查集实现,输入密码后,遍历密码的每一个字母,并把这个字母和当前密码挂到一个树上。最后有共同字母或者间接有等价关系的密码都会被挂在一颗树上。

代码

#include<bits/stdc++.h>
using namespace std;
int f[200505];
int n;
int ff(int x){
    if(f[x]==x){
        return x;
    }
    else return f[x]=ff(f[x]);
}
void he(int x,int y){
    x=ff(x);
    y=ff(y);
    if(x!=y){
        f[y]=x;
    }
}
int main(){
    cin>>n;
    for(int i=1;i<=n+200;i++){
        f[i]=i;
    }
    for(int i=1;i<=n;i++){
        string a;
        cin>>a;
        for(auto s:a){
            he(i,n+s);
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        if(ff(i)==i)
        ans++;
    }
    cout<<ans;
} 

 

posted @ 2020-04-06 21:53  _LH2000  阅读(89)  评论(0编辑  收藏  举报