CodeForces 335b Palindrome 动态规划

求给定字符串的最长回文子序列。

f[i][j]表示前i个字符已经处理到长度为j的回文子串的最右位置(为最大化答案)。

g[i][j]表示前i个字符中离i最近的字符j的位置。

有f[i][j]=max(f[i-1][j], p[f[i-1][j-2]-1][str[i]])

一种是继承前i-1字符的结果,另一种是令str[i]为当前回文子串的结尾,结果为找到f[i-1][j-2]的左端前和str[i]相等的字符。

然后f[n][t]中最大的t有解的为结果。

输出答案按照dp方程找即可。

当前查询前t个字符的话,找上一个字符的范围就是1..p[t][str[f[t][k]]]-1.

神TM数组开小了f答案全乱了。。

#include <cstdio>
#include <cstring>
#include <algorithm>
#define FOR(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int N = 50005;
char str[N]={0}, ans[N];
int p[N][26], f[N][101]={0};
int main() {
	int n, i, j, k, l = 0, t;
	scanf("%s", str+1);
	t = n = strlen(str+1);
	FOR(i,1,n) str[i]-='a';
	FOR(i,1,n) memcpy(p[i],p[i-1],sizeof(p[0])),p[i][str[i]]=i;
	FOR(i,1,n) f[i][0]=i+1,f[i][1]=i;
	FOR(i,2,n) FOR(j,2,100)
		f[i][j]=max(f[i][j],(f[i-1][j-2])?(<span style="font-family: Arial, Helvetica, sans-serif;">p[f[i-1][j-2]-1][str[i]]):(f[i-1][j]));</span>
	FOR(i,0,100) if(f[n][i]) k=i;
	while (k > 1) {
		ans[l++]=str[f[t][k]]+'a';
		t=p[t][str[f[t][k]]]-1;
		k-=2;
	}
	ans[l]=0;
	printf("%s", ans);
	if(k)printf("%c",str[f[t][k]]+'a');
	reverse(ans, ans+l);
	printf("%s", ans);
	return 0;
}


B. Palindrome
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Given a string s, determine if it contains any palindrome of length exactly 100 as asubsequence. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of s and is as long as possible.

Input

The only line of the input contains one string s of length n (1 ≤ n ≤ 5·104) containing only lowercase English letters.

Output

If s contains a palindrome of length exactly 100 as a subsequence, print any palindrome of length 100 which is a subsequence of s. If s doesn't contain any palindromes of length exactly 100, print a palindrome that is a subsequence of s and is as long as possible.

If there exists multiple answers, you are allowed to print any of them.

Sample test(s)
input
bbbabcbbb
output
bbbcbbb
input
rquwmzexectvnbanemsmdufrg
output
rumenanemur
Note

A subsequence of a string is a string that can be derived from it by deleting some characters without changing the order of the remaining characters. A palindrome is a string that reads the same forward or backward.



阅读更多
版权声明:转载请注明 http://blog.csdn.net/huanghongxun/ https://blog.csdn.net/huanghongxun/article/details/49926953
文章标签: codeforces dp
上一篇CodeForces 596B Wilbur and Array 贪心
下一篇BZOJ 2243 SDOI 2011 染色 树链剖分
想对作者说点什么? 我来说一句

动态规划题解

2013年12月22日 1KB 下载

没有更多推荐了,返回首页

关闭
关闭