题解:CF545B Equidistant String

· · 题解

题目大意

给出两个长度为 n 的字符串 a,b,让你求出一个字符串 c,使得字符串 c 与字符串 a,b 不相同的位置的个数相同。

题目思路

先使字符串 c 等于字符串 a,然后遍历一共有多少个 a,b 不相同位置,在第奇数/偶数个位置使字符串 c 等于字符串 b。最后判断两者不相同的位置有几个,奇数个输出 impossible,否则输出字符串 c。

AC Code

#include <cstring>
#include <iostream>
#include <algorithm>

#define endl '\n'
#define int long long
#define inf 0x3f3f3f3f
#define lnf 0x3f3f3f3f3f3f3f3f

//#pragma GCC optimize(1)
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
//#pragma GCC optimize("Os")
//#pragma GCC optimize("Ofast")

using namespace std;

inline bool input (int& x) {
    x = 0;
    int f = 1;
    bool flag = 0;
    char c = getchar ();

    while (!isdigit(c)) {
        if (c == '-') {
            c = getchar ();

            if (isdigit (c)) {
                f = -1;
                break;
            }
        } else {
            c = getchar ();
        }
    }

    while (isdigit (c)) {
        flag = 1;
        x = (x << 3) + (x << 1) + (c ^ 48);
        c = getchar ();
    }

    x *= f;
    return flag;
}

inline bool output (int x) {
    if (x < 0) {
        putchar ('-');
        x = -x;
    }

    char write[25], cnt = 0;

    do {
        write[++ cnt] = x % 10;
        x /= 10;
    } while (x);

    do {
        putchar (write[cnt --] | 48);
    } while (cnt);

    return x;
}

void init ();

string a, b, c;
int n, ans;

signed main () {
    init ();
    cin >> a >> b;
    n = a.size ();
//  cout << n;

    for (int i = 0; i < n; ++ i) {
        c += a[i];//这里也可以是c += b[i],只不过下面的 if 里面就变成 c[i] = a[i];

        if (a[i] != b[i]) {
            ++ ans;

            if (ans % 2) {//这里也可以是 if (ans % 2 == 1)
                c[i] = b[i];
            }
        }
    }

    if (ans % 2) {
        puts ("impossible");
    } else {
        cout << c;
    }

    return 0;
}

void init () {
//  freopen (".in", "r", stdin);
//  freopen (".out", "w", stdout);
//  ios::sync_with_stdio (false);
//  cin.tie (0);
//  cout.tie (0);
}