首爾性愛美術館18禁的藝術金豪禮★拿現金最實在!輕忽小中風,當心變殘障24天後重啟院會 兩岸...
2012-05-06 10:35:20 人氣(687) | 回應(0) | 推薦(0) | 收藏(0) 上一篇 | 下一篇

[UVA][DP] 11151 - Longest Palindrome

0
收藏
0
推薦

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;
}

11151Longest PalindromeDP
台長:Morris
人氣(687) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][Floyd] 821 - Page Hopping
此分類上一篇:[UVA][EASY][Math] 10432 - Polygon Inside A Circle

我要回應
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入以下數字 (ex:123)

(有*為必填)
詳全文