POJ 1159 Palindrome(动态规划,最大公共子列)

题目来源:http://poj.org/problem?id=1159

问题描述

Palindrome

Time Limit: 3000MS

 

Memory Limit: 65536K

Total Submissions: 67377

 

Accepted: 23448

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

------------------------------------------------------------

题意

给定一个字符串,求使这个字符串变成回文字符串最少需要添加的字符个数

------------------------------------------------------------

思路

题目可以转化为原串和逆串的最大公共子列问题,所求答案就是原串长度-原串和逆串的最大公共子列长度,因为剩下不能匹配的字符需要在合适位置新增字符一一匹配。

不同于一般的求最大公共子列问题,这题卡空间卡得比较紧。如果直接开int dp[5005][5005]的数组会MLE。解决方法有2个:

第一种是投机取巧的常数级别优化。用short dp[5005][5005],可以少占一半空间(int 4字节,short 2字节);

第二种方法是用滚动数组化二维DP为一维DP。注意到最大公共子列问题状态转移方程

dp[i][j] = dp[i-1][j-1] + 1,            s1[i-1]==s2[j-1]

         = max(dp[i-1][j], dp[i][j-1],  s1[i-1]!=s2[j-1]

中i状态只与i-1状态同理,故可以用两个一维数组dp和dp1分别表示dp[i]和dp[i-1],详见代码。

------------------------------------------------------------

代码

#include<cstdio>
#include<cstring>
#include<algorithm>

// 滚动数组方法,化二维DP数组为两个一维数组
short dp[5005];	// LCS(最大公共子列) DP
short dp1[5005];

int main()
{
#ifndef ONLINE_JUDGE
	freopen("1159.txt", "r", stdin);
#endif
	int n, i, j;
	char s1[5005], s2[5005];
	while (scanf("%d", &n) != EOF)
	{
		scanf("%s", s1);
		strcpy(s2, s1);
		std::reverse(s2, s2+n);	// 问题转化为求原串与逆串的最大公共子列长度m, n-m即为结果
		memset(dp, 0, sizeof(dp));
		memset(dp1, 0, sizeof(dp1));
		for (i=1; i<=n; i++)
		{
			for (j=1; j<=n; j++)
			{
				if (s1[i-1] == s2[j-1])
				{
					dp[j] = dp1[j-1] + 1;
				}
				else
				{
					dp[j] = std::max(dp1[j], dp[j-1]);
				}
			}
			memcpy(dp1, dp, sizeof(dp));
		}
		printf("%d\n", n - dp[n]);
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值