2012-05-06 10:35:20Morris

[UVA][DP] 11151 - Longest Palindrome

Problem D: Longest Palindrome

Time limit: 10 seconds


A 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

2
ADAM
MADAM

Sample Output

3
5


從長度小的開始做, 遞迴式如下,
另外一種方法則是反轉字串, 原字串與反轉後的字串做 LCS

#include <stdio.h>
#include <string.h>
#define max(x, y) ((x) > (y) ? (x) : (y))

int main() {
int t;
char str[1001];
short DP[1001][1001];
scanf("%d", &t);
getchar();
while(t--) {
gets(str);
memset(DP, 0, sizeof(DP));
int len = strlen(str), i, j;
for(i = 0; i < len; i++) {
for(j = 0; j + i < len; j++) {
if(str[j] == str[i+j]) {
DP[j][j+i] = DP[j+1][j+i-1] + (i == 0 ? 1 : 2);
} else {
DP[j][j+i] = max(DP[j+1][j+i], DP[j][j+i-1]);
}
}
}
printf("%d\n", DP[0][len-1]);
}
return 0;
}