codeforces 并查集_Codeforces 1263D. Secret Passwords(并查集,思维)

题意:

给n个字符串,如果任意两个字符串有一个字符相同,则他们相同即属于同一集合,问总共有几个集合

思路:

并查集,对于每个字符串,把每个字符与第一个字符合并,因为他们肯定在同一个集合(意思是每个字符串都当成ch[0],看有几个不同的),合并之后,for(1-26)以它为根的个数,即集合的个数,貌似是思维题(并查集裸题)

代码:

#include

#include

#include

#include

#include

#include

#include

#include

#include

using namespace std;

int pre[100];

int vis[100050];

int find(int x)

{

if(x==pre[x])return x;

else return pre[x]=find(pre[x]);

}

void join(int x,int y)

{

int fx=find(x),fy=find(y);

if(fx>fy)swap(fx,fy);

if(fx!=fy)pre[fx]=fy;

}

int main()

{

//freopen("in.txt","r",stdin);

int n;

char ch[100050];

for(int i=1; i<=26; ++i)pre[i]=i;

scanf("%d",&n);

for(int i=1;i<=n;i++)

{

scanf("%s",ch);

int len=strlen(ch);

int t=find(ch[0]-'a'+1);

vis[t]=1;

for(int i=1;i

{

int tt=ch[i]-'a'+1;

vis[tt]=1;

join(t,tt);//与ch[0]合并

}

}

int ans=0;

for(int i=1;i<=26;i++)

if(pre[i]==i&&vis[i]==1)//判断的前提是该字符出现过

ans++;

printf("%d\n",ans);

//printf("hello, world\n");

}

标签:pre,Passwords,1263D,int,fy,查集,fx,include,find

来源: https://www.cnblogs.com/zzl-dreamfly/p/11982195.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值