《[ARC158E] All Pair Shortest Paths》解题报告
对于这种求所有区间和的东西要么用增量法,要么拆贡献,还可以用分治的方法。
这题采用分治的方法。
对于区间
我们记
那么可以得到答案为:
考虑简化式子,变成:
我们把后面的求和拎出来。
然后考虑前面的
然后枚举
时间复杂度
#include<bits/stdc++.h>
typedef long long LL;
using namespace std;
const int MAXN=2e5+10,P=998244353;
const LL inf=1e15;
int n;
LL a[MAXN][2];
LL ans,f[MAXN][2][2],L[MAXN<<1],R[MAXN<<1],pre[MAXN<<1];
void solve(int l,int r) {
if(l==r) {
ans+=a[l][0]*3+a[l][1]*3;
ans%=P;
return ;
}
int mid=(l+r)/2;
f[mid][0][1]=f[mid][1][0]=a[mid][0]+a[mid][1];
f[mid][0][0]=a[mid][0];
f[mid][1][1]=a[mid][1];
for(int i=mid-1;i>=l;--i) {
for(int j=0;j<2;++j) {
f[i][j][0]=f[i+1][j][0]+a[i][0];
f[i][j][1]=f[i+1][j][1]+a[i][1];
f[i][j][0]=min(f[i][j][0],f[i][j][1]+a[i][0]);
f[i][j][1]=min(f[i][j][1],f[i][j][0]+a[i][1]);
}
}
f[mid+1][0][1]=f[mid+1][1][0]=a[mid+1][0]+a[mid+1][1];
f[mid+1][0][0]=a[mid+1][0];
f[mid+1][1][1]=a[mid+1][1];
for(int i=mid+2;i<=r;++i) {
for(int j=0;j<2;++j) {
f[i][j][0]=f[i-1][j][0]+a[i][0];
f[i][j][1]=f[i-1][j][1]+a[i][1];
f[i][j][0]=min(f[i][j][0],f[i][j][1]+a[i][0]);
f[i][j][1]=min(f[i][j][1],f[i][j][0]+a[i][1]);
}
}
int cnt1=0,cnt2=0;
for(int i=l;i<=mid;++i) {
for(int j=0;j<2;++j) {
ans+=f[i][1][j]%P*(r-mid)*4;
ans%=P;
L[++cnt1]=f[i][0][j]-f[i][1][j];
}
}
// cout<<ans<<" ";
for(int i=mid+1;i<=r;++i) {
for(int j=0;j<2;++j) {
ans+=f[i][1][j]%P*(mid-l+1)*4;
ans%=P;
R[++cnt2]=f[i][0][j]-f[i][1][j];
}
}
// cout<<ans<<" ";
sort(R+1,R+1+cnt2);
for(int i=1;i<=cnt2;++i) {
pre[i]=pre[i-1]+R[i];
pre[i]%=P;
// cout<<R[i]<<" ";
}
// puts("");
for(int i=1;i<=cnt1;++i) {
int ll=0,rr=cnt2+1,mid;
// cout<<L[i]<<" ";
while(ll+1<rr) {
mid=(ll+rr)/2;
if(R[mid]<-L[i]) ll=mid;
else rr=mid;
}
// cout<<L[i]<<" "<<ll<<' '<<pre[ll]<<endl;
ans+=(L[i]%P*ll+pre[ll])*2;
ans%=P;
}
// cout<<ans<<" "<<l<<" "<<r<<endl;
solve(l,mid);
solve(mid+1,r);
}
int main () {
scanf("%d",&n);
for(int i=0;i<=1;++i) {
for(int j=1;j<=n;++j) {
scanf("%lld",&a[j][i]);
}
}
solve(1,n);
ans=(ans%P+P)%P;
printf("%lld\n",ans);
return 0;
}