原题:https://www.luogu.org/problemnew/show/AT2289
题解:根据题意,可以分析出对于一个确定的区间[L,R]答案是确定的,就是每个m的最大值之和-路程。时间复杂度为:O(n^2*m)。倒过来想若B(i,j)有影响一定是第j列第[x,y]行且x<i<y,区间中的数都比B(i,j)小。很容易想到用单调栈求出每个点的左右扩展。
设f(i,j)表示选择区间(i,j)最优购买。B(i,j)就应该把f(a,b)x<a<=i ,i<=b<y全部加B(i,j)。区间的操作可以用差分的思想。
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 行
0 0 0 0 0 -> 0 1 1 1 0 0 1 0 0 -1
0 0 0 0 0 0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 -1 0 0 1
列
查询答案时先扫描列,在一行一行的推就行了。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=5e3+10;
const int M=220;
ll a[N],b[N][M],cnt[N][N];
int n,m,S[N],top,L[N][M],R[N][M];
inline int rd(){
int x=0;int f=1;char s=getchar();
while(!isdigit(s)){if(s=='-')f=-1;s=getchar();}
while(isdigit(s)) x=(x<<1)+(x<<3)+s-'0',s=getchar();
return x*f;
}
int main(){
n=rd();m=rd();a[0]=a[1]=0;
for(int i=2;i<=n;i++) a[i]=a[i-1]+1ll*rd();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) b[i][j]=1ll*rd();
for(int j=1;j<=m;j++){
top=0;
for(int i=1;i<=n;i++){
while(top && b[S[top]][j] <b[i][j] ) top--;
L[i][j]=top?S[top]+1:1;
S[++top]=i;
}
top=0;
for(int i=n;i>=1;i--){
while(top && b[S[top]][j]<b[i][j] ) top--;
R[i][j]=top?S[top]-1:n;
S[++top]=i;
}
for(int i=1;i<=n;i++){
cnt[L[i][j]][i]+=b[i][j];
cnt[L[i][j]][R[i][j]+1]-=b[i][j];
cnt[i+1][i]-=b[i][j];
cnt[i+1][R[i][j]+1]+=b[i][j];
}
}
ll ans=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++) cnt[i][j]+=cnt[i][j-1];
for(int j=1;j<=n;j++) cnt[i][j]+=cnt[i-1][j];
for(int j=i;j<=n;j++) ans=max(ans,cnt[i][j]-a[j]+a[i]);
}
printf("%lld\n",ans);
return 0;
}