题解:
分治好题
首先暴力显然rmq可以做到n^2
比较容易想到是以最值分治,这样在数据随机复杂度是nlogn,不随机还是n^2的
以最值分治只有做多与较小区间复杂度相同才是nlogn的
而这题里我们直接分治
想清楚再搞个暴力对拍还是比较好写的
代码:
#include <bits/stdc++.h> using namespace std; #define rint register int #define IL inline #define rep(i,h,t) for (rint i=h;i<=t;i++) #define dep(i,t,h) for (rint i=t;i>=h;i--) #define ll long long #define mid ((h+t)>>1) const int N=6e5; const int mo=1e9; int a[N],sum[N],sum2[N],sum3[N],sum4[N],sum5[N],sum6[N]; ll ans=0; void fz(int h,int t) { if (h==t) { ans=(ans+1ll*a[h]*a[h])%mo; return; } int mina=a[mid],maxa=a[mid]; sum[mid+1]=sum2[mid+1]=sum3[mid+1]=sum4[mid+1]=0; dep(i,mid,h) { mina=min(a[i],mina); maxa=max(a[i],maxa); sum[i]=(sum[i+1]+(1ll*mina*maxa)%mo*(mid-i+1))%mo; sum2[i]=(sum2[i+1]+1ll*mina*maxa)%mo; sum3[i]=(sum3[i+1]+1ll*(mid-i+1)*mina)%mo; sum4[i]=(sum4[i+1]+mina)%mo; sum5[i]=(sum5[i+1]+1ll*(mid-i+1)*maxa)%mo; sum6[i]=(sum6[i+1]+maxa)%mo; } mina=a[mid],maxa=a[mid]; int pos1=mid,pos2=mid; rep(i,mid,t) { mina=min(a[i],mina); maxa=max(a[i],maxa); while (a[pos1]>=mina&&pos1>=h) pos1--; pos1++; while (a[pos2]<=maxa&&pos2>=h) pos2--; pos2++; if (pos2<pos1) { ans+=(1ll*(2*i-mid-pos1+2)*(mid-pos1+1)/2)%mo*mina%mo*maxa%mo; ans+=(sum3[pos2]-sum3[pos1]+1ll*(i-mid)*(sum4[pos2]-sum4[pos1]))%mo*maxa%mo; ans+=(sum[h]-sum[pos2]+1ll*(i-mid)*(sum2[h]-sum2[pos2]))%mo; ans%=mo; } else { ans+=(1ll*(2*i-mid-pos2+2)*(mid-pos2+1)/2)%mo*mina%mo*maxa%mo; ans+=(sum5[pos1]-sum5[pos2]+1ll*(i-mid)*(sum6[pos1]-sum6[pos2]))%mo*mina%mo; ans+=(sum[h]-sum[pos1]+1ll*(i-mid)*(sum2[h]-sum2[pos1]))%mo; ans%=mo; } } if (h<=mid-1) fz(h,mid-1); if (mid+1<=t) fz(mid+1,t); } int main() { freopen("1.in","r",stdin); freopen("1.out","w",stdout); ios::sync_with_stdio(false); int n; cin>>n; rep(i,1,n) cin>>a[i]; fz(1,n); cout<<ans<<endl; return 0; }