动态规划 POJ1159 Palindrome解题报告

题目链接http://poj.org/problem?id=1159

动态规划的经典题目,有兴趣可以做一下

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

IOI 2000

  本题虽然不难,但是也需要一定的技巧。题目的意思大概就是说给你一个字符串(dp跟字符串关系不错),让你求最少的插入字符数使其成为一个回文字符串,所谓回文就是从前往后读和从后往前读是一样的,也就是说对称吧。初学者遇到此题一般会联想到把字符串分成两段(我之前就是这样想的),然后求最长公共子序列,这样并不正确,因为题目没有说在两段分别插入相同的字符数。所以应该从全局考虑:

  抽象为一般情况就是求s[i]..s[j]需要插入多少字符数(这种方法是最常见和易用的),然后根据动态规划的最优子结构思想求s[1][n]。如果能想到这一点就比较简单了。递推公式很快就能得出:

  if (s[i]=s[j])d[i][j]=d[i+1][j-1];

  else d[i][j]=min(d[i+1][j],d[i][j-1])+1;

  由一个双重循环就可以解决。这里需要注意的地方就是i,j变化的方向。i: n-1 -> 1, j: i+1 -> n。

 

#include<iostream>
#include<fstream>
using namespace std;
short d[5001][5001];//如果不用short,可能会超内存
char ch[5005];
int main()
{
	int n;
	cin>>n;
	for (int i = 1; i <= n; i++)
		cin>>ch[i];
	memset(d, 0, sizeof(d));
	for (int i = n - 1; i >= 1; i--)
		for (int j = i + 1; j <= n; j++)
		{
			if (ch[i] == ch[j])
				d[i][j] = d[i + 1][j - 1];
			else d[i][j] = min(d[i + 1][j], d[i][j - 1]) + 1;
		}
		printf("%d\n", d[1][n]);
	return 0;
}
posted @ 2011-02-12 22:10  like@neu  阅读(503)  评论(2编辑  收藏  举报