UVA 11151 Longest Palindrome(最长回文子序列 + dp + LCS)

来源:互联网 发布:ubuntu可以安装在u盘 编辑:程序博客网 时间:2024/05/29 19:47

Problem D: Longest Palindrome

Time limit: 10 seconds


palindrome is a string that reads the same from the left as it does from the right. For example, I, GAG and MADAM are palindromes, but ADAM is not. Here, we consider also the empty string as a palindrome.

From any non-palindromic string, you can always take away some letters, and get a palindromic subsequence. For example, given the string ADAM, you remove the letter M and get a palindrome ADA.

Write a program to determine the length of the longest palindrome you can get from a string.

Input and Output

The first line of input contains an integer T (≤ 60). Each of the next T lines is a string, whose length is always less than 1000.

For ≥90% of the test cases, string length ≤ 255.

For each input string, your program should print the length of the longest palindrome you can get by removing zero or more characters from it.

Sample Input

2ADAMMADAM

Sample Output

35
题意:给定一个字符串,求出去除几个字母,得到最大长度的回文串。。

思路:坑了,一开始题目没理解对,以为要连续的序列,结果用manacher算法去写WA了- -后来仔细一看才发现可以不连续啊。。。那就是dp了。把字符串倒序,求出正序和倒序的最长公共子序列即可。转化为LCS问题。

代码:

#include <stdio.h>#include <string.h>int t, i, j, d[1005][1005], len;char a[1005], b[1005];int max(int a, int b) {return a > b ? a : b;}int main () {scanf("%d%*c", &t);while (t --) {memset(d, 0, sizeof(d));gets(a);len = strlen(a);for (i = 0; i < len; i ++)b[len - 1 - i] = a[i];for (i = 1; i <= len; i ++)for (j = 1; j <= len; j ++) {if (a[i - 1] == b[j - 1])d[i][j] = d[i - 1][j - 1] + 1;elsed[i][j] = max(d[i - 1][j], d[i][j - 1]);}printf("%d\n", d[len][len]);}return 0;}



原创粉丝点击