Longest PalindromeTime Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld
& %llu
Description
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 题意: 求最长回文字串,输出其长度。 (正序,逆序最长公共子序列)。。。 CODE:#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<string> #include<algorithm> #include<cstdlib> #include<set> #include<queue> #include<stack> #include<vector> #include<map> #define N 100010 #define Mod 10000007 #define lson l,mid,idx<<1 #define rson mid+1,r,idx<<1|1 #define lc idx<<1 #define rc idx<<1|1 const double EPS = 1e-11; const double PI = acos ( -1.0 ); const double E = 2.718281828; typedef long long ll; const int INF = 1000010; using namespace std; char s[1010],ss[1010]; int dp[1010][1010]; int main() { int t; while(cin>>t) { getchar(); while(t--) { gets(s); int n=strlen(s); if(n==0) { printf("0\n"); continue; } int x=0; for(int i=n-1; i>=0; i--) ss[x++]=s[i]; ss[x]='\0'; memset(dp,0,sizeof dp); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(s[i]==ss[j]) dp[i+1][j+1]=dp[i][j]+1; else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]); } } printf("%d\n",dp[n][n]); } } return 0; }