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.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值