Square Distance
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 249 Accepted Submission(s): 86
Problem Description
A string is called a square string if it can be obtained by concatenating two copies of the same string. For example, "abab", "aa" are square strings, while "aaa", "abba" are not.
Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Peter has a string s=s1s2...sn of even length. He wants to find a lexicographically smallest square string t=t1t2...tn that the hamming distance between s and t is exact m . In addition, both s and t should consist only of lowercase English letters.
Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Peter has a string s=s1s2...sn of even length. He wants to find a lexicographically smallest square string t=t1t2...tn that the hamming distance between s and t is exact m . In addition, both s and t should consist only of lowercase English letters.
Input
There are multiple test cases. The first line of input contains an integer
T
, indicating the number of test cases. For each test case:
The first contains two integers n and m (1≤n≤1000,0≤m≤n,n is even) -- the length of the string and the hamming distance. The second line contains the string s .
The first contains two integers n and m (1≤n≤1000,0≤m≤n,n is even) -- the length of the string and the hamming distance. The second line contains the string s .
Output
For each test case, if there is no such square string, output "Impossible" (without the quotes). Otherwise, output the lexicographically smallest square string.
Sample Input
3 4 1 abcd 4 2 abcd 4 2 abab
Sample Output
Impossible abab aaaa
题意:字符串t是恰好由两个相同的串拼接的,给出一个s串,要求t恰好与s有m个位置不同。输出字典序最小的t串,不存在则输出Impossible
题解:把字符串s分成[0,n/2-1] 与 [n/2,n-1]两个部分。 dp[i][j]表示到第i位总花费(不同的位数)为j的可行性。 我们从第n/2-1为推回到第0位,如果 dp[0][m] = 1,那么表示有可行的目标串t,然后贪心将每一位从 ‘a’试到 ‘z’,选取可行的字符。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 1010
int dp[maxn][maxn];//dp[i][j]表示在第i位,总代价为j的可行性
char str[maxn];
int main()
{
int t,n,m,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
scanf("%s",str);
memset(dp,0,sizeof(dp));
dp[n/2][0]=1;
for(i=n/2-1;i>=0;--i)
{
if(str[i]==str[i+n/2])
{
for(j=0;j<=m;++j)//花费0
dp[i][j]=dp[i+1][j];
for(j=0;j<=m-2;++j)//花费2
if(dp[i+1][j])
dp[i][j+2]=1;
}
else
{
for(j=0;j<=m-1;++j)//花费1
if(dp[i+1][j])
dp[i][j+1]=1;
for(j=0;j<=m-2;++j)//花费2
if(dp[i+1][j])
dp[i][j+2]=1;
}
}
if(!dp[0][m])
{
printf("Impossible\n");
continue;
}
for(i=0;i<n/2;++i)
{
for(j=0;j<26;++j)
{
int cnt=0;
if(str[i]!=j+'a')
cnt++;
if(str[n/2+i]!=j+'a')
cnt++;
if(dp[i+1][m-cnt])
{
str[i]=j+'a';
str[i+n/2]=j+'a';
m-=cnt;
break;
}
}
}
puts(str);
}
return 0;
}