题意
有一组圆环排列的树,给出 i i i 到 i + 1 i+1 i+1( n n n 到 1)的距离 d i d_i di 和第 i i i 棵树的高度 h i h_i hi。
一只猴子每天选择两棵树 x , y x,y x,y,然后消耗 2 ( h x + h y ) + d i s t ( x , y ) 2(h_x+h_y)+dist(x,y) 2(hx+hy)+dist(x,y) 的体力,其中 d i s t ( x , y ) dist(x,y) dist(x,y) 表示 x x x 到 y y y 的距离。
每天都有孩子在 a i ∼ b i a_i\sim b_i ai∼bi 的区间内玩耍,猴子只能在其他区间内活动,因此 d i s t ( x , y ) dist(x,y) dist(x,y) 是一定的。
给出每天的 a , b a,b a,b,求猴子每天能消耗的最大体力。
分析
求区间最大值,考虑用线段树。
两棵树之间的距离可以破环成链后前缀和求解,设 s u m i sum_i sumi 为第 i i i 位之前的距离和。
不妨设 y > x y>x y>x,则原函数为 2 h x + 2 h y + s u m y − s u m x = 2 h x − s u m x + 2 h y + s u m y 2h_x+2h_y+sum_y-sum_x=2h_x-sum_x+2h_y+sum_y 2hx+2hy+sumy−sumx=2hx−sumx+2hy+sumy。
可以用线段树维护 2 h i + s u m i 2h_i+sum_i 2hi+sumi 和 2 h i − s u m i 2h_i-sum_i 2hi−sumi,然后区间查找最大值即可。(其实是很裸的线段树)
Code
#include<bits/stdc++.h>
#define ls (x<<1)
#define rs (x<<1|1)
#define mid ((l+r)>>1)
typedef long long ll;
using namespace std;
inline ll read(){ll x=0,f=1;char c=getchar();while(c<48||c>57){if(c==45)f=0;c=getchar();}while(c>47&&c<58)x=(x<<3)+(x<<1)+(c^48),c=getchar();return f?x:-x;}
const ll maxn=2e5+5;
ll n,m,d[maxn],h[maxn],sum[maxn];
struct linetree{ll v1,v2,ans;}t[maxn<<2];
inline linetree operator+(linetree a,linetree b){
return {max(a.v1,b.v1),max(a.v2,b.v2),max({a.ans,b.ans,a.v2+b.v1})};
}
inline void buildtree(ll x,ll l,ll r){
if(l==r){
t[x].v1=h[l]*2+sum[l];
t[x].v2=h[l]*2-sum[l];
return;
}
buildtree(ls,l,mid),buildtree(rs,mid+1,r);
t[x]=t[ls]+t[rs];
}
inline linetree treeask(ll x,ll s,ll e,ll l,ll r){
if(l>=s&&r<=e)return t[x];
if(e<=mid)return treeask(ls,s,e,l,mid);
else if(s>mid)return treeask(rs,s,e,mid+1,r);
return treeask(ls,s,e,l,mid)+treeask(rs,s,e,mid+1,r);
}
signed main(){
n=read(),m=read();
for(ll i=1;i<=n;++i)d[i]=d[i+n]=read();
for(ll i=1;i<=n;++i)h[i]=h[i+n]=read();
for(ll i=1;i<=n*2;++i)sum[i]=sum[i-1]+d[i-1];
buildtree(1,1,n*2);
while(m--){
ll a=read(),b=read(),ans=0;
if(a<=b){
if(a!=1)ans=max(ans,treeask(1,1,a-1,1,n<<1).ans);
if(b!=n){
ans=max(ans,treeask(1,b+1,a+n-1,1,n<<1).ans);
ans=max(ans,treeask(1,b+n+1,n<<1,1,n<<1).ans);
}
}
else ans=max(ans,treeask(1,b+1,a-1,1,n<<1).ans);
printf("%lld\n",ans);
}
}