P10244题解

· · 题解

这道题考虑用贪心策略。

不难发现,对于每个 a_i 和 c_i,都会有以下三种情况:

但是题目让我们使 a 的字典序最小,那么我们忽略 a_i<c_i,去考虑另外两种情况:

这样,我们的题目就做好了,时间复杂度 O(n)。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int n;
    cin >> n;
    string a, b, c, d;
    cin >> a >> b >> c >> d;
    for (int i = 0; i < n; i++) {
        if (a[i] > c[i]) {
            // cerr << i + 1 << " ";
            swap(b[i], d[i]);
        }
        if (a[i] == c[i]) {
            if (b[i] >= d[i]) swap(b[i], d[i]);
        }
    }
    cout << b;
}