Hamming Distance
[Link](Problem - H - Codeforces)
题意
两个长度相同字符串的 h a m m i n g D i s t a n c e hammingDistance hammingDistance为字符不同的总位数。给你两个字符串 s t r a , s t r b stra,strb stra,strb,让你找到一个字符串 r e s res res,使得 r e s res res和 s t r a , s t r b stra,strb stra,strb的 h a m m i n g D i s t a n c e hammingDistance hammingDistance相同且字典序最小。
题解
因为要满足字典序最小所以从前往后肯定 a a a填的越多越好,设sum为枚举到当前位 d i s t a − d i s t b dista-distb dista−distb的值,因为最终距离要相同所以最后 s u m sum sum一定等于零。对于每一位来说如果 s t r a i ! = s t r b i stra_i != strb_i strai!=strbi那么这一位既可以让sum加一(填 s t r b i strb_i strbi)也可以让sum减一(填 s t r a i stra_i strai)也可以不变(填一个不等于 s t r a i , s t r b i stra_i,strb_i strai,strbi的字符)。所以对于每一位判断要填某个字符是否合法就要看填完以后的 s u m su m sum和这一位以后的不同位的个数,因此我们可以用后缀和来记录不同位数的和,每次从小到大枚举26个字符,如果当前这个check成立就填就ok了。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
char stra[N], strb[N];
int sum, dist[N];
bool check(int x, char c) {
int tmp = sum;
if (stra[x] != c) tmp ++;
if (strb[x] != c) tmp --;
return abs(tmp) <= dist[x + 1];
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int T, C = 1;
cin >> T;
while (T -- ) {
cin >> stra + 1 >> strb + 1;
n = strlen(stra + 1);
dist[n + 1] = 0;
for (int i = n; i; i -- ) dist[i] = dist[i + 1] + (stra[i] != strb[i]);
cout << "Case "<< C ++ << ":"<< " ";
sum = 0;
for (int i = 1; i <= n; i ++ )
for (char c = 'a'; c <= 'z'; c ++ ) {
if (!check(i, c)) continue ;
cout << c;
if (c != stra[i]) sum ++;
if (c != strb[i]) sum --;
break;
}
cout << endl;
}
return 0;
}