码迷,mamicode.com
首页 > 其他好文 > 详细

Uva 11151 - Longest Palindrome

时间:2016-10-07 20:43:22      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

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

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.

Output

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 最长公共子序列

/* ***********************************************
Author        :guanjun
Created Time  :2016/10/7 19:14:31
File Name     :uva11151.cpp
************************************************ */
#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 10010
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
priority_queue<int,vector<int>,greater<int> >pq;
struct Node{
    int x,y;
};
struct cmp{
    bool operator()(Node a,Node b){
        if(a.x==b.x) return a.y> b.y;
        return a.x>b.x;
    }
};

bool cmp(int a,int b){
    return a>b;
}
int dp[1100][1100];
int main()
{
    #ifndef ONLINE_JUDGE
    //freopen("in.txt","r",stdin);
    #endif
    //freopen("out.txt","w",stdout);
    int t,n;
    cin>>t;
    string s,k;
    getchar();
    while(t--){
        getline(cin,s);
        k=s;
        reverse(s.begin(),s.end());
        int n=s.size();
        cle(dp);
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(s[i]==k[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]);
            }
        }
        cout<<dp[n][n]<<endl;
    }
    return 0;
}

 

Uva 11151 - Longest Palindrome

标签:

原文地址:http://www.cnblogs.com/pk28/p/5936538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!