题解:P15951 [ICPC 2018 Jakarta R] Edit Distance

· · 题解

历程

我最开始执迷不悟:认为等长字符串的编辑距离只要每位都不同就行了, 然后就直接爆炸了。

然后,过了好一会儿,我突然明白,编辑距离又不是只能修改,还有插入和删除,而两个等长字符串可以通过“删除一个字符 + 在另一位置插入一个字符”用两次操作同时改变两个位置的字符。所以编辑距离可以远小于只修改的距离。

典型例子:S = \text{"1010"},取反得到 T = \text{"0101"}。 只修改的距离是 4,但编辑距离只需 2:

因此 $edit(S,T) = 2 \not> \frac{4}{2}$,不满足题目要求。 这就是为什么我最初直接取反的代码会 WA。 :::warning[Wrong Code] ```cpp #include <bits/stdc++.h> using namespace std; #define int long long signed main() { cin.tie(0)->sync_with_stdio(0); string s; cin >> s; for (char c : s) cout << (c == '0' ? '1' : '0'); cout << '\n'; return 0; } ``` ::: ## 构造思路 统计 $S$ 中 0 和 1 的个数。 若 0 多,输出全 1:编辑距离等于 0 的个数 $> n/2$。 若 1 多,输出全 0:编辑距离等于 1 的个数 $> n/2$。 若个数相等,构造一个与 $S_0$ 不同的首位,其余位全部与 $S_0$ 相同。 例如 $S = \text{"1010"}$,首位是 1,则 $T = \text{"0111"}$,此时 $S$ 与 $T$ 的编辑距离至少为 $n/2 + 1 = 3$,满足要求。 :::success[AC Code] ```cpp #include <bits/stdc++.h> using namespace std; #define int long long signed main() { cin.tie(0)->sync_with_stdio(0); char s[2005]; cin >> s; int n = strlen(s), c0 = 0, c1 = 0; for (int i = 0; i < n; ++i) { if (s[i] == '0') c0++; else c1++; } if (c0 > c1) { for (int i = 0; i < n; ++i) cout << '1'; } else if (c1 > c0) { for (int i = 0; i < n; ++i) cout << '0'; } else { char f = s[0]; if (f == '0') { cout << '1'; for (int i = 1; i < n; ++i) cout << '0'; } else { cout << '0'; for (int i = 1; i < n; ++i) cout << '1'; } } cout << '\n'; return 0; } ``` :::