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

题目链接 

#include 

const int maxn = 100 ;

int fa[maxn],ans,n;
char s[maxn];
bool vis[maxn];

inline int find(int x){return fa[x]==x?x:fa[x]=find(fa[x]);}
inline void merge(int x,int y)
{
	x=find(x),y=find(y);
	if(x!=y)fa[x]=y;
	return ;
}
int main()
{
#ifdef LOCAL
    freopen("input.in","r",stdin);
#endif
    scanf("%d",&n);
    for(int i=1;i<=26;i++)fa[i]=i;
    for(int i=1;i<=n;i++)
    {
    	scanf("%s",s+1);
        int len=strlen(s+1);
        vis[s[1]-'a'+1]=true;
        for(int j=2;j<=len;j++)
        {
            merge(s[j-1]-'a'+1,s[j]-'a'+1);
           	vis[s[j]-'a'+1]=true;
        }
    }
    for(int i=1;i<=26;i++) if(find(i)==i&&vis[i])ans++;
    printf("%d\n",ans);
    return 0;
}

 

你可能感兴趣的:(并查集)