POJ1159

Palindrome
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 43460   Accepted: 14815

Description

A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. 

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

Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.

Output

Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

Sample Input

5

Ab3bd

Sample Output

2

Source

 
 1 #include<iostream>

 2 #include <cstdio>

 3 #include<string.h>

 4 #include<string>

 5 using namespace std;

 6 short DP[2][5003];

 7 

 8 int main(){

 9     int n;

10     string str;

11 

12     while(scanf("%d",&n)!=EOF){

13         cin>>str;

14         memset(DP,0,sizeof(DP));

15 

16         int k= 0;

17         for(int i=n-2;i>=0;i--){

18             for(int j=i;j<n;j++){

19                 if(str[i]==str[j])

20                     DP[k][j] = DP[1-k][j-1];

21                 else

22                     DP[k][j] = min(DP[1-k][j],DP[k][j-1]) + 1;

23             }

24             for(int j=0;j<n;j++) DP[1-k][j] = 0;

25             k = 1 - k;  // 循环利用的关键值k。

26         }

27         printf("%d\n",DP[1-k][n-1]);

28     }

29     return 0;

30 }

 

你可能感兴趣的:(poj)