您的位置:首页 > 大数据 > 人工智能

UVA 10617 Again Palindrome 又是回文 dp,记忆化搜索

2013-11-09 09:31 513 查看
题意:给出一个字符串,问又几种方法能够删除字符使得字符串变成回文。

记忆化搜索即可。

递归条件写错搞了老旧。。。

代码:

/*
*  Author:      illuz <iilluzen[at]gmail.com>
*  Blog:        http://blog.csdn.net/hcbbt *  File:        uva10617.cpp
*  Create Date: 2013-11-09 00:28:31
*  Descripton:  dp 
*/

#include <cstdio>
#include <cstring>

#define max(a, b) (a) > (b) ? (a) : (b)

const int MAXN = 65;

long long dp[MAXN][MAXN];
char str[MAXN];
int t;

long long solve(int beg, int end) {
	if (-1 != dp[beg][end])
		return dp[beg][end];
	if (beg >= end)
		return dp[beg][end] = (beg == end ? 1 : 0);
	else {
		if (str[beg] == str[end])
			dp[beg][end] = max(dp[beg][end], solve(beg + 1, end) + solve(beg, end - 1) + 1);
		else
			dp[beg][end] = max(dp[beg][end], solve(beg + 1, end) + solve(beg, end - 1) - solve(beg + 1, end - 1));
		return dp[beg][end];
	}
}

int main() {
	scanf("%d", &t);
	while (t--) {
		memset(dp, -1, sizeof(dp));

		scanf("%s", str);
		printf("%lld\n", solve(0, strlen(str) - 1));
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: