模拟赛 T1。
先考虑如何计算初始时能移动的方块。容易想到从后往前枚举,比较 和 的大小,如果 ,则会移动 个方块,并将 赋值为 (因为 上面的部分移动到 上了)。
然后考虑对于每一个 ,将上方方块移除后对答案的影响。令 表示从 起向左第一个方块数严格小于 的位置,则将 位置的上方方块移除后会使答案增加 (因为只会影响这一行的方块)。 用单调栈容易求出,然后枚举每一个 ,对 取 即可。
Code
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int maxn=2e5+10;
int n,t[maxn];
struct node{
int val,l;
}a[maxn];
struct stack{
int val,id;
}st[maxn];
signed main(){
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int T;
cin>>T;
while(T--){
int maxx=0,cnt=0,res=0;
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i].val,t[i]=a[i].val;
for(int i=n-1;i>=1;i--){
if(t[i]>t[i+1]) res+=t[i]-t[i+1],t[i]=t[i+1];
}
maxx=res;
for(int i=n;i>=1;i--){
while(cnt&&st[cnt].val>a[i].val) a[st[cnt].id].l=i+1,cnt--;
st[++cnt].val=a[i].val; st[cnt].id=i;
}
while(cnt) a[st[cnt].id].l=1,cnt--;
for(int i=1;i<=n;i++){
maxx=max(maxx,res+i-a[i].l);
}
cout<<maxx<<endl;
}
return 0;
}时间复杂度 。