P1435 回文字串

题目背景

IOI2000第一题

题目描述

回文词是一种对称的字符串。任意给定一个字符串,通过插入若干字符,都可以变成回文词。此题的任务是,求出将给定字符串变成回文词所需要插入的最少字符数。

比如 “Ab3bd”插入2个字符后可以变成回文词“dAb3bAd”或“Adb3bdA”,但是插入少于2个的字符无法变成回文词。

注:此问题区分大小写

输入格式

一个字符串(0<strlen<=1000)

输出格式

有且只有一个整数,即最少插入字符数

输入输出样例

输入 #1
Ab3bd
输出 #1
2


#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int n,dp[5001][5001];
char str1[5001],str2[5001];
int main(){
    scanf("%s",str1+1);
    n=strlen(str1+1);
    for(int i=1;i<=n;i++){
        str2[i]=str1[n-i+1];
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(str1[i]==str2[j]){
                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[n][n]);
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/xiongchongwen/p/11261588.html