Problem Descriptiona string is called a square string if it can be obtained by concatenating a copies of the same string . For example, "Abab", "AA" is square strings, while "AAA", "ABBA" is not.
Hamming distance between-strings of equal length is the number of positions at which the corresponding symbols was dif Ferent.
Peter has a strings =s1s 2 sn of even length. He wants to find a lexicographically smallest square string t =t1t 2 tn That the Hamming distance betweensandTis exact M.In addition, both s and T should consist only of lowercase 中文版 letters.
Inputthere is multiple test cases. The first line of input contains an integerT, indicating the number of test cases. For each test case:
The first contains and the integersNandm (1≤n≤,0≤m≤n, N is even) -The length of the string and the Hamming distance. The second line contains the string s.
Outputfor Each test case, if there is no such square string, output "impossible" (without the quotes). Otherwise, output the lexicographically smallest square string.
Test instructions: Give you a s string of length n, a number m, and now let you construct a T-string with a length of n, so that the string is made up of two identical strings, and the number of bits corresponding to the S string is different from M.
and the dictionary order of T is as small as possible.
The first thought of greed, but the obvious simple greed can not get the correct results. So we have to use the DP
Dp[i][count] indicates that the take to I bit has a count of locations that are not the same. DP[I][COUNT]+=DP[I+1][COUNT-GG] (GG indicates the number of positions to change)
There are several situations in this question.
(1) S[I]==S[I+N/2], this time will either change position or change 2 times.
(2) S[I]!=S[I+N/2], this is either changed 2 times or changed 1 times.
Since the dictionary order needs to be minimal, try to change from the first. So the recursion to start from the N/2, so as to ensure that the previous operation can make the subsequent manipulation set up.
#include <iostream> #include <cstring>using namespace Std;char s[1010];int dp[1010][1010];int main () {int t; CIN >> T; while (t--) {int n, m; CIN >> n >> m; Cin >> (s + 1); int count = m; memset (DP, 0, sizeof (DP)); DP[N/2 + 1][0] = 1; for (int i = N/2; I >= 1, i--) {if (s[i] = = S[i + N/2]) {for (int j = 0; j <= m; j+ +) {Dp[i][j] + = Dp[i + 1][j]; } for (int j = 2; J <= M; j + +) {Dp[i][j] + = Dp[i + 1][j-2]; }} else {for (int j = 1; j <= M; j + +) {Dp[i][j] + = dp[i + 1 ][J-1]; } for (int j = 2; J <= M; j + +) {Dp[i][j] + = Dp[i + 1][j-2]; }}} if (!dp[1][m]) {cout << "impossible" << Endl; Continue } for (int i = 1, i <= n/2; i++) {for (int j = 0; J <; J + +) {int temp = (s [i]! = j + ' a ') + (s[i + N/2]! = j + ' a '); if (Dp[i + 1][m-temp]) {S[i] = s[i + N/2] = j + ' a '; M-= temp; Break }}} cout << s + 1 << endl; } return 0;}
Hdu 5903 Square Distance (DP)