# HDOJ 5903 Square Distance(dp)

33 篇文章 0 订阅

## 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.

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   (1n1000,0mn,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



#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;
} 

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
08-13
11-13 95
09-30 515
09-26 183
10-22 3231
11-23 693
03-02 548
05-02 571
06-23 2540
07-05 3119
05-02 3131
04-19 2020
08-12 1758
02-09 1599

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。