P1435 Reply text string (longest common subsequence variant)

Topic portal

Question:
Give you a string, and ask you how many characters should you insert at least to make this string a palindrome?

Idea:
We can find the longest subsequence in the original string that is itself a palindrome, and then the number of remaining characters is the number of characters that should be inserted. For example: str="abcbd", in this string, the subsequence that is itself a palindrome is "bcd", then we only need to insert characters for'a' and'd'. We first store the source string in reverse order, and then directly find the longest common subsequence of the two strings.

Code:

#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;
}

Guess you like

Origin blog.csdn.net/Joker_He/article/details/108395305