并查集-图的遍历-BFS
题目大意
给出 n n n 个字符串,求出这些字符串按照题目规则,最多可以分成多少组
我们可以把每一个字母当成一个点,对于每一个给出的字符串,把字符串中的所有字母之间都连上边。这样,若两个字符串有公共的字母,他们就一定在一个连通块内,最后求出连通块个数就可以了
我们可以用并查集来简化上面的操作,对于一次加边操作,我们可以用并查集的合并来代替,最后求连通块也是同理
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int Maxn=30,inf=0x3f3f3f3f;
int f[Maxn];
bool c[Maxn];
int n,ans;
inline int read()
{
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*w;
}
int find(int x)
{
if(f[x]==x)return x;
return f[x]=find(f[x]);
}
inline void uni(int x,int y)
{
f[find(x)]=find(y);
}
int main()
{
// freopen("in.txt","r",stdin);
n=read();
for(int i=1;i<=26;++i)
f[i]=i;
for(int i=1;i<=n;++i)
{
char s[60];
scanf("%s",s+1);
int len=strlen(s+1);
c[s[1]-'a'+1]=1;
for(int j=1;j<len;++j)
{
int x=s[j]-'a'+1,y=s[j+1]-'a'+1;
uni(x,y);
c[x]=c[y]=1;
}
}
for(int i=1;i<=26;++i)
if(f[i]==i && c[i])ans++;
printf("%d\n",ans);
return 0;
}