[ABC262G] LIS with Stack
Problem Statement
There is an empty sequence $X$ and an empty stack $S$. Also, you are given an integer sequence $A=(a_1,\ldots,a_N)$ of length $N$.
For each $i=1,\ldots,N$ in this order, Takahashi will do one of the following operations:
- Move the integer $a_i$ onto the top of $S$.
- Discard the integer $a_i$ from $A$.
Additionally, Takahashi may do the following operation whenever $S$ is not empty:
- Move the integer at the top of $S$ to the tail of $X$.
The score of the final $X$ is defined as follows.
- If $X$ is non-decreasing, i.e. if $x_i \leq x_{i+1}$ holds for all integer $i(1 \leq i \lt |X|)$, where $X=(x_1,\ldots,x_{|X|})$, then the score is $|X|$ (where $|X|$ denotes the number of terms in $X$).
- If $X$ is not non-decreasing, then the score is $0$.
Find the maximum possible score.
Constraints
- $1 \leq N \leq 50$
- $1 \leq a_i \leq 50$
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
$N$ $a_1$ $\ldots$ $a_N$
Output
Print the answer.
Sample Input 1
7 1 2 3 4 1 2 3
Sample Output 1
5
The following operations make the final $X$ equal $(1,1,2,3,4)$, for a score of $5$.
- Move $a_1=1$ onto the top of $S$.
- Move $1$ at the top of $S$ to the tail of $X$.
- Move $a_2=2$ onto the top of $S$.
- Discard $a_3=3$.
- Move $a_4=4$ onto the top of $S$.
- Move $a_5=1$ onto the top of $S$.
- Move $1$ at the top of $S$ to the tail of $X$.
- Move $a_6=2$ onto the top of $S$.
- Move $2$ at the top of $S$ to the tail of $X$.
- Move $a_7=3$ onto the top of $S$.
- Move $3$ at the top of $S$ to the tail of $X$.
- Move $4$ at the top of $S$ to the tail of $X$.
We cannot make the score $6$ or greater, so the maximum possible score is $5$.
Sample Input 2
10 1 1 1 1 1 1 1 1 1 1
首先发现其实放入栈再拿出其实就是反转操作。反转后还要满足递增.为了控制递增这个条件,我们需要给 dp 定义再加上值域两维去记录。定义 \(dp_{l,r,x,y}\) 代表从第 \(l\) 个数到第 \(r\) 个数进行操作,且最终序列的数再值域 \([x,y]\) 中时,最多能放入多少个数。
考虑是否把 \(a_l\) 放入栈中,如果不放,\(dp_{l,r,x,y}=dp_{l+1,r,x,y}\)
如果放入,首先要满足 \(a_l\in [x,y]\),然后枚举我把那个数放入后再弹出 \(a_l\),如果放入\(a_j\)后弹出 \(a_l\),那么\(dp_{l,r,x,y}\) 可以从 \(dp_{l,j,x,a_l}+dp_{j+1,r,a_l,y}\)。
#include<bits/stdc++.h>
using namespace std;
const int N=55;
int n,a[N],dp[N][N][N][N];
int dfs(int l,int r,int x,int y)
{
if(l>r||x>y)
return 0;
if(~dp[l][r][x][y])
return dp[l][r][x][y];
int ans=dfs(l+1,r,x,y);
if(a[l]<x||a[l]>y)
return dp[l][r][x][y]=ans;
for(int j=l;j<=r;j++)
ans=max(ans,dfs(l+1,j,x,a[l])+dfs(j+1,r,a[l],y)+1);
return dp[l][r][x][y]=ans;
}
int main()
{
memset(dp,-1,sizeof(dp));
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",a+i);
printf("%d",dfs(1,n,1,50));
}