hdu6357 Hills And Valleys (最长不下降子序列)

题目传送门

题意:

 给你0~9的字符串,问你翻转哪个区间后使得其最长不下降子序列长度最长

思路:

 因为字符是0~9,所以我们可以定义一个b数组来枚举L,R,

 去和原来的字符串去求最长公共子序列长度,不断更新求最大值

  然后在其中记录路径,不断回缩去求此时的L,R

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define N 100005
int n,b[19];
char str[N];
int a[N],dp[N][19],pre[N][15];

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int ans=0,ansl,ansr; scanf("%d %s",&n,str);
        for(int i=0;i<n;i++) a[i+1]=str[i]-'0';
        for(int L=0;L<=9;L++)
        for(int R=L;R<=9;R++){
            int tot=0;
            for(int k=0;k<=L;k++) b[++tot]=k;
            for(int k=R;k>=L;k--) b[++tot]=k;
            for(int k=R;k<=9;k++) b[++tot]=k;
            //更新LCS
            for(int i=1;i<=n;i++)
            {
                int t=0;
                for(int j=1;j<=tot;j++)
                {
                    if(dp[i-1][j]>dp[i-1][t]) t=j;
                    pre[i][j]=t;
                    dp[i][j]=dp[i-1][t]+(a[i]==b[j]);
                }
            }
            for(int j=tot;j>=1;j--)
            if(dp[n][j]>ans){
                ans=dp[n][j];
                int t=j,l=0,r=0;
                for(int i=n;i>=0;i--){
                    if(!l&&t<=L+1) l=i+1;
                    if(!r&&t<=R+2) r=i;
                    t=pre[i][t];
                }
                if(r==0) r=l;
                ansl=l;ansr=r;
            }
        }
         printf("%d %d %d
",ans,ansl,ansr);
    }
    return 0;
}
View Code

参考博客:https://www.cnblogs.com/zquzjx/p/10333418.html

原文地址:https://www.cnblogs.com/zhgyki/p/10422634.html