Palindromic Subsequence UVA11404

逆序后求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;
}


你可能感兴趣的:(Palindromic Subsequence UVA11404)