题意:给出一个字符串A,求出需要至少插入多少个字符使得这个字符串变成回文串.
思路:设dp[i][j]为使区间[i, j]变成回文串所需要的最少字符个数.
1.A[i] == A[j的情况]那么dp[i][j] = min(dp[i][j], dp[i + 1][j -1]);
2.或者在第j个位置插入一个字符A[i], dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1);
3.或者在第i个位置插入一个字符A[j], dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1);
最后记录一下路径输出.
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;
typedef char byte;
const int MAX = 1005;
const int INF = 0x20202020;
int dp[MAX][MAX];
byte path[MAX][MAX];
char A[MAX];
int dfs(int i, int j){
if(i >= j)return 0;
else if(dp[i][j] != INF)return dp[i][j];
int & ref = dp[i][j];
if(A[i] == A[j]){
ref = dfs(i + 1, j - 1);
path[i][j] = 0;
}
int t = dfs(i + 1, j) + 1;
if(ref > t){
ref = t;
path[i][j] = 2;
}
t = dfs(i, j - 1) + 1;
if(ref > t){
ref = t;
path[i][j] = 1;
}
return ref;
}
void print_path(int i, int j){
if(i > j)return;
else if(i == j)printf("%c", A[i]);
else if(path[i][j] == 0){
printf("%c", A[i]);
print_path(i + 1, j - 1);
printf("%c", A[j]);
}else if(path[i][j] == 1){
printf("%c", A[j]);
print_path(i, j - 1);
printf("%c", A[j]);
}else if(path[i][j] == 2){
printf("%c", A[i]);
print_path(i + 1, j);
printf("%c", A[i]);
}
}
int main(int argc, char const *argv[]){
while(~scanf("%s", A)){
int n = strlen(A);
memset(dp, 0x20, sizeof(dp));
printf("%d ", dfs(0, n - 1));
print_path(0, n - 1);
printf("\n");
}
return 0;
}