思路
有合并集合这样的操作,不难想到并查集。且 很小,可以 枚举数字合并,现在的问题是如何求出 。
首先,将长度更小的数补充前导 。
此时,我们发现,当有且仅有一个满足 的数对 , 才为 。
时间复杂度 。
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 110;
int fa[MAXN];
int n;
string s[MAXN];
int cnt[MAXN];
int ans1, ans2;
int find(int x) {
if (fa[x] == x) {
return x;
}
return fa[x] = find(fa[x]);
}
void join(int c1, int c2) {
int x = find(c1), y = find(c2);
if (x != y) {
fa[x] = y;
}
}//并查集模板
bool P(string a, string b) {
if (a.size() > b.size()) {
swap(a, b);
}
int la = a.size(), lb = b.size();
while (la < lb) {
a = '0' + a;
la++;
}
int sum = 0;//不同的数位的个数
char x = '#', y = '#';//a, b 中第一个不同的
for (int i = 0; i < la; i++) {
if (a[i] != b[i]) {
sum++;
if (x != '#') {//如果已经选过
if (a[i] != y || b[i] != x) {//交换后是否合法
return 0;
}
} else {
x = a[i];
y = b[i];
}
}
}
return sum == 2;//sum = 2 才合法
}
signed main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> s[i];
fa[i] = i;
}
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (P(s[i], s[j])) {
join(i, j);
}
}
}
for (int i = 1; i <= n; i++) {
cnt[find(i)]++;
}
for (int i = 1; i <= n; i++) {
if (cnt[i]) {
ans1++;
ans2 = max(ans2, cnt[i]);
}
}
cout << ans1 << ' ' << ans2;
return 0;
}