题意:给定一个字符串,任意位置添加字母形成回文字串,最少添加几个字母.
思路:把字符串反转,求反转串和原串的最长公共子序列,ans=n-lcs
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX_N = 5005;
char s[MAX_N], t[MAX_N];
int dp[3][MAX_N + 1];
int main()
{
int n;
while(cin >> n) {
cin >> s;
memset(dp, 0, sizeof(dp));
for (int i = n - 1, j = 0; i >= 0; --i) {
t[i] = s[j++];
}
int e = 0;
for(int i = 0; i < n; ++i) {
e = 1 - e;
for(int j = 0; j < n; ++j) {
if(s[i] == t[j]) {
dp[e][j + 1] = dp[1 - e][j] + 1;
} else {
dp[e][j + 1] = max(dp[1 - e][j + 1], dp[e][j]);
}
}
}
cout << n - dp[e][n] << endl;
}
return 0;
}
本文介绍了一种通过计算最长公共子序列来确定在给定字符串基础上构建最短回文串所需最少字符添加数的方法。该方法首先反转原始字符串并与之比较,利用动态规划找出两者的最长公共子序列长度。
2701

被折叠的 条评论
为什么被折叠?



