应该是最简洁易懂的做法了。
Observation 1:每个点的最终状态是一段区间。设为 。
Observation 2:对于两个点 ,如果 ,则 ,取等条件为 。
那么我们可以考虑记忆化搜索。具体而言,初始时将所有 设为 。每次搜索一个点,尽可能往两侧扩展。比如可以扩展到 ,那么就继续搜索 ,并把 并入 (由 Observation 2 容易证明正确性)。如果一个点已经搜过,不需要再次搜索,因此复杂度显然为 。
总共只需要写一个前缀和,写一个 dfs,不用任何数据结构,且复杂度是高贵的线性。
#include<bits/stdc++.h>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
#define pii pair<ll,ll>
#define rep(i,a,b) for(ll i=(a);i<=(b);++i)
#define per(i,a,b) for(ll i=(a);i>=(b);--i)
using namespace std;
bool Mbe;
ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void write(ll x){
if(x<0)putchar('-'),x=-x;
if(x>9)write(x/10);
putchar(x%10+'0');
}
const ll N=5e5+9;
ll n,C[N],L[N],R[N],sum[N],pre[N];
bool mem[N];
vector<ll>e[N];
void Merge(ll x,ll y){
L[x]=min(L[x],L[y]),R[x]=max(R[x],R[y]),sum[x]=pre[R[x]]-pre[L[x]-1];
}
void solve(ll x){
if(mem[x])return ;
mem[x]=1,L[x]=R[x]=x,sum[x]=C[x];
while(1){
bool exd=0;
if(L[x]>1&&C[L[x]-1]<sum[x])solve(L[x]-1),Merge(x,L[x]-1),exd=1;
if(R[x]<n&&C[R[x]+1]<sum[x])solve(R[x]+1),Merge(x,R[x]+1),exd=1;
if(!exd)break;
}
}
bool Med;
int main(){
cerr<<fabs(&Med-&Mbe)/1048576.0<<"MB\n";
n=read();
rep(i,1,n)C[i]=read(),pre[i]=pre[i-1]+C[i];
rep(i,1,n)solve(i);
rep(i,1,n)write(sum[i]),putchar(' ');
putchar('\n');
cerr<<"\n"<<clock()*1.0/CLOCKS_PER_SEC*1000<<"ms\n";
return 0;
}