D. Secret Passwords

原题链接

题解

把两个含有相同字符的字符串放进一个集合里,这让我想到了并查集

这里是线性并集,遍历字符串,对于字符串中出现的字符的集合并到自己身上来

code

#include<bits/stdc++.h>
using namespace std;
int occ[30]={0};
int fa[200005];
int finds(int now){return fa[now]==now?now:fa[now]=finds(fa[now]);}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        fa[i]=i;
        string s;
        cin>>s;
        int flag=0;
        for(int j=0;s[j];j++)
        {
            int now=s[j]-'a';
            if(occ[now])
            {
                fa[finds(occ[now])]=i;
            }
            else occ[now]=i;
        }
    }

    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(finds(i)==i) ans++;
    }

    cout<<ans;
    return 0;
}

posted @ 2024-03-19 14:53  纯粹的  阅读(13)  评论(0)    收藏  举报