HDOJ 5903 Square Distance(dp)

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
 

题意:字符串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;
} 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值