Description
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.
More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print - 1.
Input
The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n).
The second line contains string s1 of length n, consisting of lowercase English letters.
The third line contain string s2 of length n, consisting of lowercase English letters.
Output
Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.
Sample Input
3 2 abc xyc
ayd
1 0 c b
-1
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
char s1[100002], s2[100002];
int result[100002];
bool vis[100002];
int equ;
int main(){
int n, i, j, t;
int same;
while(~scanf("%d%d", &n, &t)){
memset(vis, 0, sizeof(vis));
scanf("%s", &s1);
scanf("%s", &s2);
same = 0;
for( i = 0; i < n; ++i){
if(s1[i] == s2[i]){
vis[i] = 1;
++same;
}
}
t = n - t;
int flag = 0;
if(t <= same){
int ss = t;
for(i = 0; i < n; ++i){
if(vis[i] == 1 && ss != 0){
result[i] = s1[i] - 0;
--ss;
}
else {
for(j = 97; j <= 122; ++j){
if(j != (s1[i] - 0) && j != (s2[i] - 0)){
result[i] = j;
break;
}
}
}
}
}
else if(t > same){
if(2 * (t - same) > (n - same)){
cout << "-1" << endl;
flag = 1;
}
else {
int t1 = t - same;
int t2 = t - same;
for(i = 0; i < n; ++i){
if(vis[i] == 1)
result[i] = s1[i] - 0;
else if(vis[i] != 1 && t1 > 0){
result[i] = s1[i] - 0;
--t1;
}
else if(vis[i] != 1 && t2 > 0){
result[i] = s2[i] - 0;
--t2;
}
else {
for(j = 97; j <= 122; ++j){
if(j != (s1[i] - 0) && j != (s2[i] - 0)){
result[i] = j;
break;
}
}
}
}
}
}
if(flag == 0){
for(i = 0; i < n; ++i){
printf("%c", result[i]);
}
cout << endl;
}
}
return 0;
}
题目大意: 第一行给出两个数,n, t,第二~三行分别给出两个字符串s1, s2,长度为 n, 接下来要输出的答案也是一个字符串,长度为n, 要求输出的字符串与先前给出的两个字符串各有t个不同的字符。
这一道题目有个坑点就是他说不同的字符,是指同一位置上的,如果s1 = abc, s2 = bca, 那么他们是有3个不同的字符,而不是0个, 对应位置各不相同,理解了这一点这个题目就容易做了,因为对字符的操作我容易出错, 所以就用了ASCII码来存的。
该题目分为两种情况,我是求的相同的字符,因为有t个不同的字符不就是有(n - t) 个相同的字符吗。我用 t = n - t ;就是求分别与两个字符串有t个相同字符的字符串。
先用same来保存相同的个数,同时设一个vis数组来保存那个位置相同,然后判断一下 (1)当 t < same 的时候, 相同的个数已经满足了,就从相同的字符中选择t 个就行,.
(2) 当 t > same 时, 相同的个数不满足,先减去相同的个数,那么剩下的字符数, 就是 t - same 的个数应该满足 2 * (t - same) <= (n - same), 这是判断可不可以找到所求的字符串, 如满足就继续找该字符串, 若不满足就找不到该字符串,直接输出 -1 。