题解 UVA11404 【Palindromic Subsequence】

题目链接:Link

Solution

这题的状态转移方程很容易想出(分同时去掉、去头、去尾三种情况),但字典序最小不好处理。我是在状态转移的同时计算答案,没想到string居然没有炸掉....

贴代码:

#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=1005;
char s[maxn];
int n,dp[maxn][maxn];
string res[maxn][maxn];
int main()
{
#ifdef local
	freopen("pro.in","r",stdin);
#endif
	while(scanf("%s",s)==1)
	{
		n=strlen(s);
		for(int len=1;len<=n;len++)
			for(int L=0;L+len<=n;L++)
			{
				int R=L+len-1;
				if(L==R)//特判
				{
					dp[L][R]=1;
					res[L][R]=s[L];
				}
				else
				{
					dp[L][R]=dp[L+1][R-1]+(s[L]==s[R]?2:0);
					dp[L][R]=max(dp[L][R],dp[L+1][R]);
					dp[L][R]=max(dp[L][R],dp[L][R-1]);
                    //分同时去掉、去头、去尾三种情况
					res[L][R]="{";//为了更新
					if(dp[L][R]==dp[L+1][R-1]+(s[L]==s[R]?2:0))
					{
						if(s[L]==s[R])
							res[L][R]=s[L]+res[L+1][R-1]+s[R];
						else
							res[L][R]=res[L+1][R-1];
					}
					if(dp[L][R]==dp[L+1][R])
						res[L][R]=min(res[L][R],res[L+1][R]);
					if(dp[L][R]==dp[L][R-1])
						res[L][R]=min(res[L][R],res[L][R-1]);
				}
//				printf("dp[%d][%d]=%d ",L,R,dp[L][R]);
//				printf("res[%d][%d]=%s\n",L,R,res[L][R].c_str());
			}
		printf("%s\n",res[0][n-1].c_str());//输出
	}
	return 0;
}
/*
Sample Input
aabbaabb
computer
abzla
samhita

Sample Output
aabbaa
c
aba
aha
*/
posted @ 2019-08-19 21:58  happyZYM  阅读(104)  评论(0编辑  收藏  举报