uva 10453 - Make Palindrome(dp)
题目大意:给出一个字符串,通过插入字符使得原字符串变成一个回文串,要求插入的字符个数最小,并且输出最后生成的回文串。
解题思路:和uva 10739的做法相似,只是本题只能插入字符,所以只要在考虑子问题的同时记录住最优的选择就可以了。
#include <stdio.h> #include <string.h> const int N = 1005; int n, dp[N][N], rec[N][N]; char str[N]; int solve() { n = strlen(str); memset(dp, 0, sizeof(dp)); memset(rec, 0, sizeof(rec)); for (int i = n - 1; i >= 0; i--) { for (int j = i + 1; j < n; j++) { if (str[i] == str[j]) dp[i][j] = dp[i + 1][j - 1]; else { if (dp[i + 1][j] > dp[i][j - 1]) { dp[i][j] = dp[i][j - 1] + 1; rec[i][j] = 1; } else { dp[i][j] = dp[i + 1][j] + 1; rec[i][j] = -1; } } } } return dp[0][n - 1]; } void print(int a, int b) { if (a > b) return; // printf("%d!\n", rec[a][b]); if (a == b) printf("%c", str[a]); else if (rec[a][b] == 0) { printf("%c", str[a]); print(a + 1, b - 1); printf("%c", str[a]); } else if (rec[a][b] == 1) { printf("%c", str[b]); print(a, b - 1); printf("%c", str[b]); } else { printf("%c", str[a]); print(a + 1, b); printf("%c", str[a]); } } int main() { while (gets(str)) { printf("%d ", solve()); print(0, n - 1); printf("\n"); } return 0; }