标签:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#define N 1005
using namespace std;
typedef long long ll;
char s[N];
int dp[N][N], rec[N][N], len;
void DP() {
len = strlen(s);
memset(dp, 0, sizeof(dp));
for (int i = len - 1; i >= 0; i--) {
for (int j = i + 1; j < len; j++) {
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1];
} else {
if (dp[i + 1][j] < dp[i][j - 1]) {
dp[i][j] = dp[i + 1][j] + 1;
rec[i][j] = -1;
} else {
dp[i][j] = dp[i][j - 1] + 1;
rec[i][j] = 1;
}
}
}
}
}
void myprint(int a, int b) {
if (a > b) return;
if (a == b) printf("%c", s[a]);
else if (rec[a][b] == 0) {
printf("%c", s[a]);
myprint(a + 1, b - 1);
printf("%c", s[a]);
} else if (rec[a][b] == 1) {
printf("%c", s[b]);
myprint(a, b - 1);
printf("%c", s[b]);
} else if (rec[a][b] == -1) {
printf("%c", s[a]);
myprint(a + 1, b);
printf("%c", s[a]);
}
}
int main() {
while (scanf("%s", s) != EOF) {
memset(rec, 0, sizeof(rec));
DP();
printf("%d ", dp[0][len - 1]);
myprint(0, len - 1);
printf("\n");
}
return 0;
}
uva 10453 Make Palindrome (区间DP + 递归输出)
标签:
原文地址:http://blog.csdn.net/llx523113241/article/details/45648997