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

时间:2022-08-07 15:42:50

链接:

https://codeforces.com/contest/1263/problem/D

题意:

One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of n passwords — strings, consists of small Latin letters.

Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords a and b as follows:

two passwords a and b are equivalent if there is a letter, that exists in both a and b;

two passwords a and b are equivalent if there is a password c from the list, which is equivalent to both a and b.

If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.

For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:

admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";

admin's password is "d", then you can access to system by using only "d".

Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

思路:

set记录每个字符出现的字符串。

遍历一边并查集维护

代码:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5+10; int Fa[MAXN];
string s[MAXN];
set<int> vec[26];
int n; int GetF(int x)
{
if (Fa[x] == x)
return Fa[x];
Fa[x] = GetF(Fa[x]);
return Fa[x];
} int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
for (int i = 1;i <= n;i++)
Fa[i] = i;
for (int i = 1;i <= n;i++)
{
cin >> s[i];
for (int j = 0;j < (int)s[i].size();j++)
vec[s[i][j]-'a'].insert(i);
}
for (int i = 0;i < 26;i++)
{
int h = *vec[i].begin();
int th = GetF(h);
for (auto v: vec[i])
{
int tr = GetF(v);
if (tr != th)
Fa[tr] = th;
}
}
int ans = 0;
for (int i = 1;i <= n;i++)
if (GetF(i) == i) ans++;
cout << ans << endl; return 0;
}