UVa 11151 - Longest Palindrome

本文介绍了一种求解最长回文子序列问题的方法:通过计算原字符串与其反转字符串之间的最长公共子序列来实现。该算法使用动态规划,并提供了一个C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求最长回文子序列,将所给字符串反制后,求与原串的最长公共子序列


// File Name: UVa11151.cpp
// Author: Toy
// Created Time: 2013年05月05日 星期日 22时07分03秒

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <utility>
#include <bitset>
#define L(x) x << 1
#define R(x) x << 1 | 1

using namespace std;

int Case, a[1000][1000];
string s1, s2;

int LCS ( const string s1, const string s2 ) {
    int len = s1.length ( );
    a[0][0] = 0;
    for ( int i = 1; i <= len; a[i][0] = 0, ++i ) ;
    for ( int j = 1; j <= len; a[0][j] = 0, ++j ) ;

    for ( int i = 1; i <= len; ++i ) 
	for ( int j = 1; j <= len; ++j ) {
	    if ( s1[i - 1] == s2[j - 1] ) a[i][j] = a[i - 1][j - 1] + 1;
	    else a[i][j] = max ( a[i][j - 1], a[i - 1][j] );
	}
    return a[len][len];
}

int main ( ) {
    cin >> Case;
    getchar ( );
    while ( Case-- ) {
	getline ( cin, s1 );
	s2.clear ( );
	for ( int i = s1.size ( ) - 1; i >= 0; s2 += s1[i], --i ) ;

	cout << LCS ( s1, s2 ) << endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值