每个点有两个值Li 和 Bi,求Li + Rj (i < j) 的最大值,这个可以用线段树巧妙的维护。。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define PII pair<int, int> #define y1 skldjfskldjg #define y2 skldfjsklejg using namespace std; const int N = 2e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; int n, m; LL d[N], h[N], sum[N]; struct node { LL mx1, mx2, mx3; node operator + (const node &rhs) const { node ans; ans.mx1 = max(mx1, rhs.mx1); ans.mx2 = max(mx2, rhs.mx2); ans.mx3 = max(mx3, rhs.mx3); ans.mx3 = max(ans.mx3, mx1 + rhs.mx2); return ans; } } a[N << 2]; void build(int l, int r, int rt) { if(l == r) { a[rt].mx1 = 2 * h[l] - sum[l - 1]; a[rt].mx2 = 2 * h[l] + sum[l - 1]; a[rt].mx3 = -INF; return; } int mid = l + r >> 1; build(l, mid, rt << 1); build(mid + 1, r, rt << 1 | 1); a[rt] = a[rt << 1] + a[rt << 1 | 1]; } node query(int L, int R, int l, int r, int rt) { if(l >= L && r <= R) return a[rt]; int mid = l + r >> 1; if(R <= mid) return query(L, R, l, mid, rt << 1); if(L > mid) return query(L, R, mid + 1, r, rt << 1 | 1); return query(L, R, l, mid, rt << 1) + query(L, R, mid + 1, r, rt << 1 | 1); } int main() { scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++) scanf("%lld", &d[i]), d[i + n] = d[i]; for(int i = 1; i <= n; i++) scanf("%lld", &h[i]), h[i + n] = h[i]; for(int i = 1; i <= 2 * n; i++) sum[i] = sum[i - 1] + d[i]; build(1, 2 * n, 1); while(m--) { int L, R; scanf("%d%d", &L, &R); L--, R--; L = (L - 1 + n) % n; R = (R + 1) % n; L++, R++; swap(L, R); if(L > R) R += n; printf("%lld ", query(L, R, 1, 2 * n, 1).mx3); } return 0; } /* */