题解:AT_waipc_qual_g Sum of Max of Sum of K Segments
暴力思路就是 dp,但是我们希望式子简洁。先对坐标进行变换,将
将
若确定了
考虑优化。观察到答案具有单调性,因此对于每个
那么只要转移
注意上述做法需要
:::success[点击查看参考代码]
#include<bits/stdc++.h>
#define TIME chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count()
#define rep(i,l,r) for(int qwp=(r),i=(l);i<=qwp;i++)
#define per(i,r,l) for(int qwp=(l),i=(r);i>=qwp;i--)
#define pb push_back
#define fir first
#define sec second
using namespace std;namespace c0dE1ng{
typedef long long ll;typedef pair<int,ll> pil;
constexpr ll llinf=3e18;constexpr int mod=998244353,N=2.5e5+5,M=5;
int n,m;ll a[N],b[M*2][N],ans,A[2][N],f[N];
int s1[N],t1,s2[N],t2;
ll hd,dlt[N];int nx[N];vector<pil>F[N];
int getnx(int u){return nx[u]==u?u:nx[u]=getnx(nx[u]);}
void main(){
cin.tie(0)->sync_with_stdio(0);
cin>>n>>m;rep(i,1,n)cin>>a[i],a[i]+=a[i-1];n-=m,m--;
rep(_,1,m<<1){
rep(i,0,n)b[_][i]=a[i+_/2+1]*(_&1?-1:1);
ll mn=llinf;rep(i,0,n)mn=min(mn,b[_][i]);
ans=(ans+mn)%mod;rep(i,0,n)b[_][i]-=mn;
}
rep(i,0,n)A[0][i]=max(a[i],a[i+1]),A[1][i]=max(-a[i],-a[i+1]);
ll mn=*min_element(A[0],A[0]+n+1);ans=(ans+mn)%mod;rep(i,0,n)A[0][i]-=mn;
mn=*min_element(A[1],A[1]+n+1);ans=(ans+mn)%mod;rep(i,0,n)A[1][i]-=mn;
ans=ans*((n+1)*1ll*(n+2)/2%mod)%mod;
s1[0]=s2[0]=n+1;per(l,n,0){
int x=t1;while(x&&A[0][l]>=A[0][s1[x]])x--;
ll w=A[0][l];rep(i,x+1,t1){ll t=w-A[0][s1[i]];w-=t,F[l].pb({s1[i-1]-1,t});}
F[l].pb({s1[t1]-1,w}),s1[t1=x+1]=l;
x=t2;while(x&&A[1][l]>=A[1][s2[x]])x--;
w=A[1][l];rep(i,x+1,t2){ll t=w-A[1][s2[i]];w-=t,F[l].pb({s2[i-1]-1,t});}
F[l].pb({s2[t2]-1,w}),s2[t2=x+1]=l;
}
rep(_,1,m<<1){
hd=llinf;per(i,n,0){
nx[i]=i,dlt[i]=hd,hd=0;vector<pil>G;
F[i].pb({i,b[_][i]});for(auto t:F[i]){
hd+=t.sec;int p=getnx(t.fir);while(1){
if(t.sec<dlt[p]){dlt[p]-=t.sec,G.pb({p,t.sec});break;}
G.pb({p,dlt[p]}),t.sec-=dlt[p];
if(p==n)break;nx[p]=p+1,p=getnx(p);
}
}F[i]=G;
}
}
rep(i,0,n)for(auto t:F[i])ans=(ans+t.sec*(t.fir-i+1)%mod*(i+1))%mod;
cout<<(ans=(ans+mod)%mod)<<'\n';
}
}
int main(){
// [[maybe_unused]]auto bot1=freopen("ksum.in","r",stdin);
// [[maybe_unused]]auto bot2=freopen("ksum.out","w",stdout);
auto _Tbe=TIME;c0dE1ng::main();auto _Ted=TIME;
return cerr<<"\nTIME:"<<_Ted-_Tbe<<"ms\n",0;
}
/*
ulimit -s 1048576
g++ -O2 -std=c++14 -static ksum.cpp -o %;size %;./%
*/
:::