题目大意:给出一个字符串,通过插入字符使得原字符串变成一个回文串,要求插入的字符个数最小,并且输出最后生成的回文串。
解题思路:和uva 10739的做法相似,只是本题只能插入字符,所以只要在考虑子问题的同时记录住最优的选择就可以了。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; char str[1050]; int DP[1050][1050]; void print(int i, int j) { if (i == j) { printf("%c", str[i]); } if (i >= j) return; if (str[i] == str[j]) { printf("%c", str[i]); print(i + 1, j - 1); printf("%c", str[j]); } else if (DP[i][j] == DP[i][j-1] + 1) { printf("%c", str[j]); print(i, j - 1); printf("%c", str[j]); } else { printf("%c", str[i]); print(i + 1, j); printf("%c", str[i]); } } int main() { while (scanf("%s", str) != EOF) { int len = strlen(str); for (int i = 0; i < len; i++) for (int j = 0; j < len; j++) DP[i][j] = 0; for (int i = len-1; i >= 0; i--) for (int j = i + 1; j < len; j++) if (str[i] == str[j]) DP[i][j] = DP[i+1][j-1]; else DP[i][j] = min(DP[i+1][j], DP[i][j-1]) + 1; printf("%d ", DP[0][len-1]); print(0, len - 1); printf("\n"); } return 0; }