POJ 1159 最少添加几个字母构成回文 DP

来源:互联网 发布:薛之谦女装店淘宝店 编辑:程序博客网 时间:2024/05/14 06:56
设原序列S的逆序列为S' ,则这道题目的关键在于,最少需要补充的字母数 = 原序列S的长度 -  S和S'的最长公共子串长度http://www.cnblogs.com/en-heng/p/3963803.html#include<iostream>#include<queue>#include<algorithm>#include<stdlib.h>#include<stdio.h>#include<iomanip>#include<string.h>using namespace std;const int MAX=5005;int Len;int F[2][MAX];char Str1[MAX];char Str2[MAX];int main(){    cin.sync_with_stdio(false);    while (cin>>Len)    {        cin>>Str1;        for (int i=Len-1;i>=0;i--)            Str2[i]=Str1[Len-1-i];        Str2[Len]='\0';        memset(F,0,sizeof(F));        int k=0,ans=0;        for (int i=0;i<Len;i++)        {            for (int j=0;j<Len;j++)            {                if (Str1[i]==Str2[j])                {                    F[k][j]=F[k^1][j-1]+1;                    ans=max(ans,F[k][j]);                }                else                    F[k][j]=max(F[k^1][j],F[k][j-1]);            }            k=k^1;        }        cout<<Len-ans<<endl;    }    return 0;}
0 0
原创粉丝点击