Palindrome
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 6
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
Input
Output
Sample Input
5 Ab3bd
Sample Output
2
Source
/*
dp[i][j]=max(dp[i+1][j-1]+same(i,j),dp[i+1][j],dp[i][j-1])
same(i,j):若str[i]==str[j],则返回1,否则返回0
空间复杂度:O(N^2);
优化:
用数组A[]记录dp[i+1][j-1]、dp[i+1][j];
用数组dp[]记录dp[j]、dp[j-1];
空间复杂度:O(N);
*/
#include<iostream>
#include<malloc.h>
#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 5001;
char str[MAXN];
int dp[MAXN],A[MAXN];
int N;
int maxx(int a, int b){
if (a<b)
return b;
return a;
}
void ss(){
int i, j;
memset(dp, 0, sizeof(dp));
memset(A,0,sizeof(A));
for (i = N; i > 0; i--){ //注意这里顺序要逆序,否则wa
for (j = 1; j <= N; j++){
if (str[i] == str[j]){
dp[j] = A[j - 1] + 1;
}
else{
dp[j] = maxx(A[j], dp[j - 1]);
}
}
for (j = 1; j <= N; j++){
A[j] = dp[j];
}
}
cout << N - dp[N] << endl;
}
int main(){
int i;
freopen("in.txt", "r", stdin);
while(~scanf("%d", &N)){
for (i = 1; i <= N; i++){
cin >> str[i];
}
ss();
}
return 0;
}