Codeforces 1263D.Secret Passwords(并查集 思维)

简介: Codeforces 1263D.Secret Passwords(并查集 思维)

linkkkk

题意:

给出n字符串,如果两个字符串中含有相同的字母说明两个字符串相同,问有多少个不同的字符串。

思路:

具有传递性,如果a , b相同,b , c相同,那么a , c也一定相同

考虑用并查集维护。

但是n < = 2 e 5所以枚举两个字符串显然不现实。

一共只有26个字母,维护在某个字符串里每个字母的出现次数,如果u , v两个字母在这个字符串里都出现过,合并u , v所在集合,这样就能实现传递性了。

代码:

// Problem: D. Secret Passwords
// Contest: Codeforces - Codeforces Round #603 (Div. 2)
// URL: https://codeforces.com/problemset/problem/1263/D
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)
#include<iostream>
#include<cstdio> 
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<sstream>
using namespace std;
typedef long long ll;
const int maxn=2e5+100;
int root[30],vis[30],siz[30];
int Find(int x){
  if(x!=root[x]) root[x]=Find(root[x]);
  return root[x];
}
int main() {
  for(int i=0;i<=27;i++) root[i]=i;
  int n;cin>>n;
  for(int i=1;i<=n;i++){
    string s;cin>>s;
    memset(siz,0,sizeof siz);
    for(int j=0;s[j];j++){
      int now=s[j]-'a'+1;
      siz[now]++;vis[now]=1;
    }
    for(int j=1;j<=26;j++){
      if(!siz[j]) continue;
      for(int k=1;k<=26;k++){
        if(!siz[k]) continue;
        int fu=Find(j),fv=Find(k);
        if(fu!=fv) root[fu]=fv;
      }
    }
  }
  int ans=0;
  for(int i=1;i<=26;i++){
  //  if(i<=4) cout<<i<<" "<<Find(i)<<" "<<ans<<endl;
    if(vis[i]&&i==Find(i)) ans++;
  }
  cout<<ans<<endl;
  return 0;
}
目录
相关文章
|
9月前
|
算法 Java 程序员
【手绘算法】力扣 20 有效的括号(Valid Parentheses)
Hi,大家好,我是Tom。一个美术生转到Java开发的程序员。今天给大家分享的是力扣题第20题,有效的括号。在解题过程中,也会手写一些伪代码。当然,如果想要完整的源码的话,可以到我的个人主页简介中获取。 这道题呢比较简单,但是曾经成为B站的算法面试题,而且通过率只有44.5%。
58 0
|
11月前
|
文件存储
Easy Number Challenge(埃式筛思想+优雅暴力)
Easy Number Challenge(埃式筛思想+优雅暴力)
62 0
【algorithm】算法基础课---二分查找算法(附笔记 | 建议收藏)
【algorithm】算法基础课---二分查找算法(附笔记 | 建议收藏)
【algorithm】算法基础课---二分查找算法(附笔记 | 建议收藏)
|
人工智能 BI
Codeforces 1324 D-Pair of Topics(思维+二分 || 双指针)
Codeforces 1324 D-Pair of Topics(思维+二分 || 双指针)
107 0
|
人工智能
Codeforces-Adding Powers(进制问题+思维)
Codeforces-Adding Powers(进制问题+思维)
70 0
CF979B Treasure Hunt(贪心 思维)
CF979B Treasure Hunt(贪心 思维)
72 0
CF979B Treasure Hunt(贪心 思维)
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
AtCoder Beginner Contest 216 D - Pair of Balls (思维建图 拓扑排序判断有向图是否有环)
94 0