Square Distance
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 192 Accepted Submission(s): 61
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.
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 .
3 4 1 abcd 4 2 abcd 4 2 abab
Impossible abab aaaa
【解题方法】参考: http://www.cnblogs.com/nicetomeetu/p/5905924.html
把字符串折半,分成0 - n/2-1 和 n/2 - n-1
dp[i][j] 表示 第i位及之后的总代价为j可不可行
从第 n/2-1 位推回第 0 位, 若dp[0][m] = 1,则存在
然后贪心对每一位从'a'试到'z',选取接下来存在解的字符
【AC 代码】
//
//Created by just_sort 2016/9/26 9:58
//Copyright (c) 2016 just_sort.All Rights Reserved
//
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int dp[maxn][maxn];//dp[i][j]表示第i位及之后的总代价为j是否可行
char s[maxn];
int main()
{
int T,n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
scanf("%s",s);
//INIT
memset(dp,0,sizeof(dp));
dp[n/2][0] = 1;
//change state
for(int i=n/2; i>=0; i--){
if(s[i] == s[i+n/2]){
for(int j = 0; j <= m; j++) dp[i][j] = dp[i+1][j]; //no change
for(int j = 0; j <= m-2; j++) if(dp[i+1][j]) dp[i][j+2] = 1; //change two
}else{
for(int j = 0; j <= m-1; j++) if(dp[i+1][j]) dp[i][j+1] = 1; //change one
for(int j = 0; j <= m-2; j++) if(dp[i+1][j]) dp[i][j+2] = 1; //change two
}
}
//get ans
if(!dp[0][m]){
puts("Impossible");
continue ;
}
int k = m;
for(int i = 0; i < n/2; i++)
{
for(int j = 0; j < 26; j++){
int p = 0;
if(s[i] != j+'a') p++;
if(s[i+n/2] != j+'a') p++;
if(dp[i+1][k-p]){
s[i] = j + 'a';
s[i+n/2] = j + 'a';
k = k - p;
break;
}
}
}
puts(s);
}
return 0;
}
700



被折叠的 条评论
为什么被折叠?



