模板——线段树维护最大子段和 SP1716 GSS3 - Can you answer these queries III

${\color{Pink}{>>Question}}$

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <cstring>
 5 #include <cmath>
 6 #define ll long long
 7 using namespace std;
 8 
 9 template <typename T> void in(T &x) {
10     x = 0; T f = 1; char ch = getchar();
11     while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
12     while(isdigit(ch)) {x = 10*x + ch - '0'; ch = getchar();}
13     x *= f;
14 }
15 
16 template <typename T> void out(T x) {
17     if(x < 0) putchar('-'),x = -x;
18     if(x > 9) out(x/10);
19     putchar(x%10 + '0');
20 }
21 
22 //------------------------------------------------------------
23 
24 const int N = 50005;
25 
26 int n,q,a;
27 
28 struct node {
29     int lm,rm,all,sum;
30 }t[N<<2];
31 
32 void P_up(node &u,node ls,node rs) {
33     u.sum = ls.sum + rs.sum;
34     u.all = max(max(ls.all,rs.all),ls.rm+rs.lm);
35     u.lm = max(ls.lm,ls.sum+rs.lm); u.rm = max(rs.rm,rs.sum+ls.rm);
36     u.all = max(u.all,max(u.lm,u.rm));
37 }
38 
39 void Build(int u,int l,int r) {
40     if(l == r) {in(a); t[u].lm = t[u].rm = t[u].all = t[u].sum = a; return;}
41     int mid = (l+r)>>1;
42     Build(u<<1,l,mid); Build(u<<1|1,mid+1,r);
43     P_up(t[u],t[u<<1],t[u<<1|1]);
44 }
45 
46 void A(int u,int l,int r,int x,int k) {
47     if(l == r) {t[u].all = t[u].lm = t[u].rm = t[u].sum = k; return;}
48     int mid = (l+r)>>1;
49     if(x <= mid) A(u<<1,l,mid,x,k); else A(u<<1|1,mid+1,r,x,k);
50     P_up(t[u],t[u<<1],t[u<<1|1]);
51 }
52 
53 node Q(int u,int l,int r,int x,int y) {
54     if(x <= l && y >= r) {return t[u];}//important
55     int mid = (l+r)>>1;
56     if(y <= mid) return Q(u<<1,l,mid,x,y);
57     else if(x > mid) return Q(u<<1|1,mid+1,r,x,y);
58     else {
59         node _u,ls,rs;
60         ls = Q(u<<1,l,mid,x,mid); rs = Q(u<<1|1,mid+1,r,mid+1,y);
61         P_up(_u,ls,rs);
62         return _u;
63     }
64 }
65 
66 int main() {
67     int op,x,y; in(n);
68     Build(1,1,n);
69     in(q);
70     while(q--) {
71         in(op); in(x); in(y);
72         if(!op) A(1,1,n,x,y);
73         else out(Q(1,1,n,x,y).all),putchar('\n');
74     }
75     return 0;
76 }

 

posted @ 2019-09-02 08:22  陈星卿  阅读(168)  评论(0编辑  收藏  举报