跳到正文

题解

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

_burbur_约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年3月27日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P15951

版本

  1. v1当前

历程

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

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

典型例子:S="1010"S = \text{"1010"},取反得到 T="0101"T = \text{"0101"}。 只修改的距离是 44,但编辑距离只需 22: "1010"→"101"→"0101"\text{"1010"} \to \text{"101"} \to \text{"0101"}。 因此 edit(S,T)=2≯42edit(S,T) = 2 \not> \frac{4}{2},不满足题目要求。

这就是为什么我最初直接取反的代码会 WA。

Wrong Code
C++
#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;
}

构造思路

统计 SS 中 0 和 1 的个数。

若 0 多,输出全 1:编辑距离等于 0 的个数 >n/2> n/2。

若 1 多,输出全 0:编辑距离等于 1 的个数 >n/2> n/2。

若个数相等,构造一个与 S0S_0 不同的首位,其余位全部与 S0S_0 相同。 例如 S="1010"S = \text{"1010"},首位是 1,则 T="0111"T = \text{"0111"},此时 SS 与 TT 的编辑距离至少为 n/2+1=3n/2 + 1 = 3,满足要求。

AC Code
C++
#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;
}
原文
存档评论3 条抓取于