题目链接
题意:给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。
求正序和逆序的最长公共子序列,再用长度-去求的值
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define ll long long
#define lowbit(x) (x&(-x))
#define MT(a, b) memset(a,b,sizeof(a))
const int maxn = 1E3 + 15;
const int ONF = -0x3f3f3f3f;
const int INF = 0x3f3f3f3f;
char str1[maxn];
char str2[maxn];
int dp[maxn][maxn];
int main() {
while (~scanf ("%s",str1)){
int len1=strlen(str1);
for (int j=0;j<len1;j++){
str2[j]=str1[len1-j-1];
}
for (int i=1;i<=len1;i++){
for (int j=1;j<=len1;j++){
if (str1[i-1]==str2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
} else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
printf("%d\n",len1-dp[len1][len1]);
}
return 0;
}
附:最长公共子序列代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=1005;
char a[maxn];
char b[maxn];
int dp[maxn][maxn];
int main ()
{
int len1,len2,ans;
while (~scanf ("%s%s",a,b))
{
memset (dp,0,sizeof(dp));
len1=strlen(a);
len2=strlen(b);
for (int i=1; i<=len1; i++)
{
for (int j=1; j<=len2; j++)
{
if (a[i-1]==b[j-1])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
printf ("%d\n",dp[len1][len2]);
}
return 0;
}