其他分享
首页 > 其他分享> > Codeforces Round #603 (Div. 2) D. Secret Passwords

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

作者:互联网

题意

给定n个字符串

如果存在一个或多个字母同时在字符串a和b中出现 这a和b就被分在同一组
如果a和c在同一组 b和c在同一组 则a和b也在同一组

问所有的字符串最后被分成几组

思路

一道并查集好题
把每一个字母当成一个点,对于每一个给出的字符串,把字符串中的所有字母之间都连上边。这样,若两个字符串有公共的字母,他们就一定在一个连通块内,用并查集维护即可

\(code\)

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+2019;
int fa[30];
int n;
int find(int x)
{
    if(fa[x]==x) return x;
    else return fa[x]=find(fa[x]);
}
int visit[30];
int ans;
int main()
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    cin>>n;
    for(int i=1;i<=26;++i) fa[i]=i;
    for(int i=1;i<=n;++i)
    {
        char s[N];
        scanf("%s",s+1);
        int len=strlen(s+1);
        for(int j=1;j<=len;++j) visit[s[j]-'a'+1]=1;
        for(int j=1;j<len;++j)
        {
            int fx=find(s[j]-'a'+1),fy=find(s[j+1]-'a'+1);
            if(fx!=fy) fa[fx]=fy;
        }
    }
    for(int i=1;i<=26;++i) 
        if(visit[i]==1&&fa[i]==i) ans++;
    cout<<ans;
    return 0;
}

标签:Passwords,return,一组,603,int,字母,Codeforces,fa,字符串
来源: https://www.cnblogs.com/pyyyyyy/p/12104636.html