hdoj-5903 Square Distance

本文探讨了一个算法问题,即如何找到与给定字符串具有特定汉明距离的字典序最小的平方字符串。通过动态规划方法解决了这一挑战,并提供了完整的代码实现。

原题链接

Square Distance

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 245    Accepted Submission(s): 83


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

dp[i][j]表示第i个字符到n/2个字符以及i+n/2到n个字符与原字符串之间的距离是否能为j

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxn 100005
using namespace std;
typedef long long ll;

char str[1005];
int dp[505][1005];
int main(){
	
	//freopen("in.txt", "r", stdin);
	int t;
	
	scanf("%d", &t);
	while(t--){
		int n, m;
		scanf("%d%d%s", &n, &m, str+1);
		memset(dp, 0, sizeof(dp));
		dp[n/2+1][0] = 1;
		for(int i = n/2; i > 0; i--){
			if(str[i] == str[i+n/2]){
				for(int j = 0; j <= m; j++)
				 dp[i][j] = dp[i+1][j];
				for(int j = 0; j <= m-2; j++){
					if(dp[i+1][j])
					 dp[i][j+2] = 1;
				}
			}
			else{
				for(int j = 0; j <= m-1; j++)
				 dp[i][j+1] = dp[i+1][j];
				for(int j = 0; j <= m-2; j++)
				 if(dp[i+1][j])
				  dp[i][j+2] = 1;
			}
		}
		if(dp[1][m] == 0)
		 puts("Impossible");
		else{
			int k = m;
			for(int i = 1; i <= n/2; i++){
				for(int j = 0; j <= 25; j++){
					int p = 0;
					if(str[i] != j + 'a')
					  p++;
					if(str[i+n/2] != j + 'a')
					 p++;
			       
					if(dp[i+1][k-p]){
						str[i] = str[i+n/2] = j + 'a';
						k -= p;
						break;
					}
				}
			}
			puts(str+1);
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值