1263 - D. Secret Passwords (并查集)

题目

思路:从答案上来看我们可以知道密码数最多只有26种即26个字母,然后根据可以等效的的密码(即直接或间接拥有相同的字母),我们让可以等效的密码放在一个集合里(对每个密码让每一个字母与第一个字母连边构成一个连通图(并查集)),然后最后的集合数即为答案。

Code:

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<memory.h>
#include<cmath>
#define pii pair<int,int>
#define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
const int Max = 2e5 + 5;
string str;
int f[30];
int book[30];

int getf(int n)
{
    
    
	if (f[n] == n)return n;
	return f[n] = getf(f[n]);
}

void merge(int a, int b)
{
    
    
	if (getf(a) != getf(b))f[getf(b)] = a;
}

int main()
{
    
    
	int n;cin >> n;
	for (int i = 1;i <= 26;i++) f[i] = i;
	for (int i = 1;i <= n;i++)
	{
    
    
		cin >> str;int a = str[0] - 'a' + 1;book[a] = 1;
		for (int j = 1;j < str.size();j++)
		{
    
    
			int b = str[j] - 'a' + 1;
			book[b] = 1;
			merge(a, b);
		}
	}
	int sum = 0;
	for (int i = 1;i <= 26;i++)if (i == f[i]&&book[i])sum++;
	cout << sum << endl;
}

猜你喜欢

转载自blog.csdn.net/asbbv/article/details/112724284