Solution of IOI2000 - 回文字串
Way 1
观察到回文串正反读一样的性质,我们把原数组反序存储在数组B中
分析原数组和B数组的子序列,可以发现这一部分本来就是回文的
然后我们找到他们的最长公共子序列,这一部分是不用改动的,对于剩下的部分我们添加同样多的字符就珂以转化为回文啦!
Way2
区间Dp
好想点吧
设区间[i,j]的最优解为Dp[i][j] ,
如果str[i]=str[j] , 那么Dp[i][j] = Dp[i-1][j-1]
否则:Dp[i][j] = min(Dp[i-1][j] , Dp[i][j-1])+1 ;
输出Dp[1][N] ,注意初始化为0
demo:
//Code By TYQ
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std ;
int Dp[1005][1005] ;
char str[1005] ;
int Len ;
int main(){
scanf("%s",str) ;
Len = strlen(str) ;
//cout<<Len<<endl;
memset(Dp,0,sizeof(Dp)) ;
for(int i=Len-1;i>=0;--i){
for(int j=i+1;j<Len;++j){
if (str[i]==str[j]) Dp[i][j] = Dp[i+1][j-1] ;
else Dp[i][j] = min(Dp[i+1][j] , Dp[i][j-1]) + 1 ;
}
}
printf("%d\n",Dp[0][Len-1]) ;
}
Copyright © 2018,谭意青
All rights served ;