CodeForces 584C - Marina and Vasya(构造)

C. Marina and Vasya
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
input
3 2
abc
xyc
output
ayd
input
1 0
c
b
output
-1

题意:
对于长度为n的两个字符串,要构造一个新的字符串,使得他与任意的字符串都有对应位置的t个不同字符.

解题思路:
对于这个字符串,必然和原字符串有n-t个相同.
那么在找相同的时候,选择a和b相同的是最优解.
记录a和b相同的个数为sum.
那么对于a和新字符串,他们最多的相同个数为sum + (n-sum)/2 (因为也需要和b有(n-sum)/2相同).
所以最大相同个数如果小于n-t,必然是不成立的.

在优先填充完sum部分后,再分别对于a和b进行单独相同填充.
最后的剩余部分要使得与a和b都不相同.

AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
char a[maxn];
char b[maxn];
char c[maxn];
int main()
{
    int n,t;
    cin>>n>>t;
    cin>>a>>b;
    int sum = 0;
    for(int i = 0;a[i];i++) if(a[i] == b[i])    sum++;
    int m = n-t;
    if(sum + (n-sum)/2 < m)
    {
        printf("-1");
        return 0;
    }
    int k = min(sum,m);
    int cnt = 0;
    for(int i = 0,cnt = 1;a[i]&&cnt <= k;i++)   if(a[i] == b[i])    c[i] = a[i],cnt++;
    int s = m-k;
    for(int i = 0,cnt = 1;a[i] && cnt <= s;i++) if((a[i] != b[i]) && !c[i]) c[i] = a[i],cnt++;
    for(int i = 0,cnt = 1;a[i] && cnt <= s;i++)  if((a[i] != b[i]) && !c[i]) c[i] = b[i],cnt++;
    for(int i = 0;a[i];i++)
    {
        if(!c[i])
        {
            for(char j = 'a';j <= 'z';j++)
                if(j != a[i] && j != b[i])  {c[i] = j;break;}
        }
    }
    cout<<c;
    return 0;
}
发布了172 篇原创文章 · 获赞 7 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章