【动态规划】最长上升子序列模型:登山_蓝桥杯

思路:求以i结尾的最长上升子序列长度和以i开始的最长下降子序列之和-1的最大值

用dp1[i]表示以i结尾的最长上升子序列长度。

用dp2[i]表示以i开始的最长下降子序列长度。

其中dp2[i]可以看成以i结尾逆序的最长上升子序列长度。

#include<iostream>
using namespace std;
int n;
int dp1[1001];
int dp2[1001];
int h[1001];
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>h[i];
    }
    for(int i=0;i<n;i++){
        dp1[i]=dp2[i]=1;
    }
    for(int i=1;i<n;i++){
        for(int j=0;j<i;j++){
            if(h[j]<h[i]){
                dp1[i]=max(dp1[i],dp1[j]+1);
            }
        }
    }
    for(int i=n-1;i>=0;i--){
        for(int j=n-1;j>i;j--){
            if(h[j]<h[i]){
                dp2[i]=max(dp2[i],dp2[j]+1);
            }
        }
    }
    int res=0;
    for(int i=0;i<n;i++){
        res=max(res,dp1[i]+dp2[i]-1);
      //cout<<dp1[i]<<" "<<dp2[i]<<endl;
    }
    cout<<res;
    return 0;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.