Palindromic Subsequence UVA11404

78 篇文章 2 订阅
55 篇文章 0 订阅

逆序后求LCS,然后找出i+j == len情况的最长最小的LCS(子序列在1~i中出现,且其逆序列在i+1到len中出现,对应于回文串偶数情况), (i+j == len-1情况的最长最小的LCS+str[i+1])(子序列在1~iz中出现,且其逆序在i+2到len中出现,注意其中包括子序列为空的情况,即回文串中只有一个字符,对应于回文串奇数情况),从这俩种情况中找出最优解



#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <queue>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#include <cctype>
#include <utility>   
#include <map>
#include <string>  
#include <climits> 
#include <set>
#include <string> 
#include <sstream>
#include <utility>
#include <ctime>
 
using std::priority_queue;
using std::vector;
using std::swap;
using std::stack;
using std::sort;
using std::max;
using std::min;
using std::pair;
using std::map;
using std::string;
using std::cin;
using std::cout;
using std::set;
using std::queue;
using std::string;
using std::istringstream;
using std::make_pair;
using std::greater;
using std::endl;

const int MAXN(1010);

struct NODE
{
	int len;
	string str;
	friend bool operator < (const NODE &op1, const NODE &op2)
	{
		return op1.len == op2.len? op1.str > op2.str: op1.len < op2.len;
	}
};

char str1[MAXN], str2[MAXN];
NODE table[MAXN][MAXN];
NODE ans;


int main()
{
	while(~scanf("%s", str1+1))
	{
		int len = strlen(str1+1);
		for(int i = 1; i <= len; ++i)
			str2[i] = str1[len-i+1];
		for(int i = 0; i <= len; ++i)
		{
			table[i][0].len = 0;
			table[i][0].str.clear();
			table[0][i].len = 0;
			table[0][i].str.clear();
		}
		for(int i = 1; i <= len; ++i)
			for(int j = 1; j <= len; ++j)
			{
				if(str1[i] == str2[j])
				{
					table[i][j].len = table[i-1][j-1].len+1;
					table[i][j].str = table[i-1][j-1].str+str1[i];
				}
				else
					if(table[i][j-1] < table[i-1][j])
						table[i][j] = table[i-1][j];
					else
						table[i][j] = table[i][j-1];
			}
		ans.len = 0;
		ans.str.clear();
		for(int i = 1; i < len; ++i)
			if(ans< table[i][len-i])
				ans = table[i][len-i];
		ans.len *= 2;
		NODE temp;
		for(int i = 0; i < len; ++i)
		{
			temp = table[i][len-i-1];
			temp.len = temp.len*2+1;
			temp.str += str1[i+1];
			if(ans < temp)
				ans = temp;
		}
		strcpy(str1+1, ans.str.c_str());
		int tl = ans.len/2;
		for(int i = 1; i <= tl; ++i)
			putchar(str1[i]);
		for(int i = ans.len&1? tl+1: tl; i >= 1; --i)
			putchar(str1[i]);
		putchar('\n');
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值