题目传送门
题意:
给你一个字符串,问你至少插入多少个字符,才能使这个字符串成为回文字符串?
思路:
我们可以把原来字符串中本身就是回文的最长子序列找到,然后剩下的字符个数就是应该插入的字符个数了。比如:str=“abcbd”,这个字符串中,本身就是回文的子序列是"bcd",那么我们只需要针对’a’和’d’插入字符就可以了。我们首先把源字符串倒序存储,然后直接求两个字符串的最长公共子序列就可以了。
代码:
#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define pii pair<int,int>
#define pdd pair<double,double>
#define lowbit(x) x&-x
#define unmap unordered_map
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read()
{
int x=0,f=1;
char ch=gc();
while(ch<'0'||ch>'9')
{
if(ch=='-')
f=-1;
ch=gc();
}
while(ch>='0'&&ch<='9')
{
x=x*10+ch-'0';
ch=gc();
}
return x*f;
}
using namespace std;
const int N=2e3+1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-6;
const double PI=acos(-1);
char s[N],t[N];
int dp[N][N];
signed main()
{
cin>>s+1;
int len=strlen(s+1);
for(int i=len;i>=1;i--)
t[i]=s[len-i+1];
for(int i=1;i<=len;i++)
{
for(int j=1;j<=len;j++)
{
dp[i][j]=max(dp[i-1][j],max(dp[i][j-1],dp[i-1][j-1]));
if(s[i]==t[j])
{
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
}
}
}
cout<<len-dp[len][len]<<endl;
}