1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <bits/stdc++.h> #define ios ios::sync_with_stdio(0),cin.tie(0); #define int long long #define N 100005 #define INF 500000000000000 using namespace std; int arr[N],n,m;
struct Node{ int sum; int lmax; int rmax; int tmax; }seg[N<<2];
void modify(Node &cur,Node &left,Node &right){ cur.sum = left.sum+right.sum; cur.lmax = max(left.lmax,left.sum+right.lmax); cur.rmax = max(right.rmax,right.sum+left.rmax); cur.tmax = max(max(left.tmax,right.tmax),left.rmax+right.lmax); }
void build(int l,int r,int cur){ if(r<=l)return; if(r-l==1){ seg[cur] = {arr[l],arr[l],arr[l],arr[l]}; return; } int mid = (l+r)/2; build(l,mid,2*cur); build(mid,r,2*cur+1); modify(seg[cur],seg[2*cur],seg[2*cur+1]); }
Node query(int cur,int l,int r,int ql,int qr){ if(r<=l || ql>=r || qr<=l)return {-INF,-INF,-INF,-INF}; if(ql<=l && qr>=r)return seg[cur]; int mid = (l+r)/2; auto left = query(2*cur,l,mid,ql,qr); auto right = query(2*cur+1,mid,r,ql,qr); Node temp; modify(temp,left,right); return temp; }
signed main(){ ios; cin>>n>>m; for(int i=1;i<=n;i++)cin>>arr[i]; build(1,n+1,1); while(m--){ int l,r;cin>>l>>r; auto ans = query(1,1,n+1,l,r+1); cout<<max(ans.tmax,(long long)0)<<endl; } }
|