POJ 1159:Palindrome 最长公共子序列

Palindrome
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 56273   Accepted: 19455

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

题意是要求给定的字符串添加多少个会变成回文字符串,实际上就是要比较该字符串和它的逆序字符串的最长公共子序列,而不是字串!!!(之前WA就WA在这里),再用长度-最长公共子序列的长度就是结果。

代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;

short int dp[5002][5002];
char b[5002];
string b_reverse;
int num;

void cal()
{
	int i,j,max_value=0;

	memset(dp,0,sizeof(dp));

	for(i=0;i<num;i++)
	{
		for(j=0;j<num;j++)
		{
			if(b[i]==b_reverse[j])
			{
				dp[i+1][j+1]=dp[i][j]+1;
			}
			else
			{
				dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
			}
			max_value=max(max_value,(int)dp[i+1][j+1]);
		}
	}
	cout<<num-max_value<<endl;
}

int main()
{
	scanf("%d",&num);
	scanf("%s",b);

	b_reverse=b;
	reverse(b,b+num);

	cal();

	return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2015-08-10 10:46  光速小子  阅读(388)  评论(0编辑  收藏  举报

导航