UVA11151 Longest Palindrome最长回文

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA11151 Longest Palindrome最长回文相关的知识,希望对你有一定的参考价值。

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 xample, 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

问题链接UVA11151 Longest Palindrome
问题简述:(略)
问题分析:最长回文问题,用动态规划来解决,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA11151 Longest Palindrome */

#include <bits/stdc++.h>

using namespace std;

const int L = 1024;
short int dp[L][L];

int main()
{
    int t;
    scanf("%d", &t);
    getchar();
    while (t--) {
        string s;
        getline(cin, s);

        memset(dp, 0, sizeof dp);
        for (int i = 0; s[i]; i++)
            for (int j = 0; s[j + i]; j++)
                if (s[j] == s[j + i])
                    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][s.size() - 1]);
    }

    return 0;
}

以上是关于UVA11151 Longest Palindrome最长回文的主要内容,如果未能解决你的问题,请参考以下文章

UVA10191 Longest Nap排序

UVA 10100 Longest Match

UVA10405 Longest Common SubsequenceLCS+DP

UVA 10405 Longest Common Subsequence

UVa 10100 - Longest Match

UVA10285 Longest Run on a Snowboard