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.
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.
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.
3 2 abc xyc
ayd
1 0 c b
-1
先找出两个字符串不同的个数,如果两个字符串中的某个不一样,那输出的字符串的那个位置要和两个字符串都不一样,如果是一样的,就都一样,计算两个字符串不一样的个数,如果不一样的个数比t小,那就从相同的地方变成不相同的,如果是比t大,那就分别从两头开始,把不一样的差数补上,达到要求,第一个字符串的比较从头开始,第二个字符串的比较从尾开始,这样就不会重复更改某个位置的字符了。
还有就是注意输出,一开始我是用printf("%s\n",ans);输出的,然后WA了好久,后来把答案逐个字符输出才A的,后来试着用cout输出,也不行。
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
int n,t;
char a[100010];
char b[100010];
char ans[100010];
scanf("%d %d",&n,&t);
scanf("%s %s",a,b);
int num=0;
for(int i=0;i<n;i++)
{
if(a[i]!=b[i]) num++; //不同的数目
}
if(num<=t)
{
int k=t-num;
for(int i=0;i<n;i++)
{
if(a[i]==b[i])
{
if(!k) ans[i]=a[i];
else
{
for(int j='a';j<='z';j++)
{
if(j!=a[i]&&j!=b[i])
{
ans[i]=j;
break;
}
}
k--;
}
}
else
{
for(int j='a';j<='z';j++)
{
if(j!=a[i]&&j!=b[i])
{
ans[i]=j;
break;
}
}
}
}
for(int i=0;i<n;i++)
{
if(ans[i]<'a'||ans[i]>'z')
{
for(int j='a';j<='z';j++)
{
if(j!=a[i]&&j!=b[i])
{
ans[i]=j;
break;
}
}
}
}
}
else
{
int p=0;
for(int i=0;i<n;i++)
{
if(a[i]==b[i])
{
ans[i]=a[i];
p++;
}
else
{
for(int j='a';j<='z';j++)
{
if(j!=a[i]&&j!=b[i])
{
ans[i]=j;
break;
}
}
}
}
int k=n-t-p;
for(int i=0;i<n;i++)
{
if(a[i]!=b[i]&&k)
{
ans[i]=a[i];
k--;
}
if(!k) break;
}
k=n-t-p;
for(int i=n-1;i>=0;i--)
{
if(a[i]!=b[i]&&k)
{
ans[i]=b[i];
k--;
}
if(!k) break;
}
}
int k=0;
int kk=0;
for(int i=0;i<n;i++)
{
if(ans[i]!=a[i]) k++;
if(ans[i]!=b[i]) kk++;
}
int flag=0;
if(k!=t||kk!=t) flag=1;
if(flag) printf("-1\n");
else
{
for(int i=0;i<n;i++) printf("%c",ans[i]);
printf("\n");
}
return 0;
}