题解 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
*/
本作品由happyZYM采用知识共享 署名-非商业性使用-相同方式共享 4.0 (CC BY-NC-SA 4.0) 国际许可协议(镜像(简单版)镜像(完整版))进行许可。
转载请注明出处:https://www.cnblogs.com/happyZYM/p/11380011.html (近乎)全文转载而非引用的请在文首添加出处链接。