题解 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 @   happyZYM  阅读(109)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示