题解:AT_abc483_e [ABC483E] Typo Pairs
题目传送门
思路
一个比较简单的做法。
直接
因为题目要求的汉明距离都
abc
||(两个字符串相同)
abc
若汉明距离为
ship => shp(删除第三位 'i')
||
shop => shp(删除第三位 'o')
同理,为
foot => ft(删除第二,三位 'oo')
||
feat => ft(删除第二,三位 'ea')
于是我们就可以很快地想到写一个专门用来求有多少对字符串的距离恰好为 count(x, y),统计删去
//n, m, s[] 分别用来存储题目中的 n, m 与题目输入的 n 个字符串
unordered_map<string, int> mp;
int count(int x, int y) {
mp.clear(); //因为后续可能多次调用,先清空
int ans = 0;
for (int i = 1; i <= n; i++) {
string t; //开一个临时变量记录删位后字符串
for (int j = 1; j <= m; j++) {
if (j == x || j == y) continue;
t += s[i][j]; //只追加未被删除的位置
}
ans += mp[t]; //与前面 mp[t] 个字符串产生字符串对
mp[t]++; //自己加入 mp[t]
}
return ans;
}
一次调用平均时间
若我们分别记录
int w0 = count(-1, -1), w1 = 0, w2 = 0; //count(-1, -1) 即不删除任何位置
for (int i = 1; i <= m; i++) w1 += count(i, -1); //count(i, -1) 即只删除 i
for (int i = 1; i < m; i++) {
for (int j = i + 1; j <= m; j++) { //m^2 循环删位
w2 += count(i, j);
}
}
到这里其实就没有剩下多少代码了。
接下来我们便可以输出 w2 了……吗?
不,因为有些字符串可能被重复统计了,例如:
abc
adc
这个字符串被 a = a 和 c = c)。
所以我们还需要一些简单的操作来处理重复。我们大可以列一个表来记录不同距离带来的贡献。
| 汉明距离为多少 | 对 |
对 |
对 |
原因 |
|---|---|---|---|---|
| 完全不合法 | ||||
| 显然只给 |
||||
| 给 |
||||
现在我们想要把上面的汉明距离
解出 c
考虑汉明距离为
解出 b
考虑汉明距离为
代入
解出 a
考虑汉明距离为
展开组合数,代入
我们对
当然,如果你并不熟悉因式分解,你也可以直接用原式
综上,我们得到:
用 m = 4 验证一下
此时
- 距离为
0 ,Ans = 3 - 2 \times 4 + \binom{4}{2} = 3 - 8 + 6 = 1 。 - 距离为
1 ,Ans = -2 + (4 - 1) = 1 。 - 距离为
2 ,Ans = 1 。 - 距离
\ge 3 ,Ans = 0 。
完美!
于是:
int ans = w2 - (m - 2) * w1 + (m - 1) * (m - 2) / 2 * w0;
cout << ans;
即可 AC。
时间复杂度:
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
int n, m;
string s[200005];
unordered_map<string, int> mp;
int count(int x, int y) {
mp.clear(); //因为后续可能多次调用,先清空
int ans = 0;
for (int i = 1; i <= n; i++) {
string t; //开一个临时变量记录删位后字符串
for (int j = 1; j <= m; j++) {
if (j == x || j == y) continue;
t += s[i][j]; //只追加未被删除的位置
}
ans += mp[t]; //与前面 mp[t] 个字符串产生字符串对
mp[t]++; //自己加入 mp[t]
}
return ans;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> s[i];
s[i] = " " + s[i]; //0-index to 1-index
}
int w0 = count(-1, -1), w1 = 0, w2 = 0; //count(-1, -1) 即不删除任何位置
for (int i = 1; i <= m; i++) w1 += count(i, -1); //count(i, -1) 即只删除 i
for (int i = 1; i < m; i++) {
for (int j = i + 1; j <= m; j++) { //m^2 循环删位
w2 += count(i, j);
}
}
int ans = w2 - (m - 2) * w1 + (m - 1) * (m - 2) / 2 * w0; //上文推出来的公式
cout << ans;
return 0;
}