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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章