1 struct node
2 {
3 int l,r,sum,add,setv,minn,maxn;
4 }tree[1<<];
5 void build(int id,int l,int r){
6 tree[id].l = l;
7 tree[id].r = r;
8 tree[id].add = 0;
9 tree[id].setv = 0;
10 if(l == r){
11 tree[id].sum = tree[id].minn = tree[id].maxn = a[l];
12 return;
13 }
14 int mid = (l+r)>>1;
15 build(id<<1,l,mid);
16 build(id<<1|1,mid+1,r);
17 maintain(id);
18 }
19 void updateSet(int id,int l,int r,int val){
20 if(tree[id].l >= l && tree[id].r <= r){
21 tree[id].setv = val;
22 tree[id].minn = val;
23 tree[id].maxn = val;
24 tree[id].add = 0;
25 tree[id].sum = (tree[id].r-tree[id].l+1)*val;
26 return;
27 }
28 pushdown(id);
29 int mid = (tree[id].l+tree[id].r)>>1;
30 if(l <= mid)
31 updateSet(id<<1,l,r,val);
32 if(mid < r)
33 updateSet((id<<1)+1,l,r,val);
34 maintain(id);
35 }
36 void updateAdd(int id,int l,int r,int val){
37 if(tree[id].l >= l && tree[id].r <= r){
38 tree[id].add += val;
39 tree[id].minn += val;
40 tree[id].maxn += val;
41 tree[id].sum += (tree[id].r-tree[id].l+1)*val;
42 return;
43 }
44 pushdown(id);
45 int mid = (tree[id].l+tree[id].r)>>1;
46 if(l <= mid)
47 updateAdd(id<<1,l,r,val);
48 if(mid < r)
49 updateAdd((id<<1)+1,l,r,val);
50 maintain(id);
51 }
52 void query(int id,int l,int r)//查询
53 {
54 if(tree[id].l >= l && tree[id].r <= r){
55 anssum += tree[id].sum;
56 ansmin = min(ansmin,tree[id].minn);
57 ansmax = max(ansmax,tree[id].maxn);
58 return;
59 }
60 pushdown(id);
61 int mid = (tree[id].l+tree[id].r)>>1;
62 if(l <= mid)
63 query(id<<1,l,r);
64 if(mid < r)
65 query(id<<1|1,l,r);
66 maintain(id);
67 }
68 void maintain(int id)//向上回溯
69 {
70 if(tree[id].l >= tree[id].r)
71 return ;
72 tree[id].maxn = max(tree[id<<1].maxn,tree[id<<1|1].maxn);
73 tree[id].minn = min(tree[id<<1].minn,tree[id<<1|1].minn);
74 tree[id].sum = tree[id<<1].sum + tree[id<<1|1].sum;
75 }
76 void pushdown(int id)//延时更新
77 {
78 if(tree[id].l >= tree[id].r)
79 return;
80 if(tree[id].setv){
81 tree[id<<1].setv = tree[id<<1|1].setv = tree[id].setv;
82 tree[id<<1].minn = tree[id<<1|1].minn = tree[id].setv;
83 tree[id<<1].maxn = tree[id<<1|1].maxn = tree[id].setv;
84 tree[id<<1].add = tree[id<<1|1].add = 0;
85 tree[id<<1].sum = (tree[id<<1].r-tree[id<<1].l+1)*tree[id].setv;
86 tree[id<<1|1].sum = (tree[id<<1|1].r-tree[id<<1|1].l+1)*tree[id].setv;
87 tree[id].setv = 0;
88 }
89 if(tree[id].add){
90 int tmp = tree[id].add;
91 tree[id<<1].add += tmp;tree[id<<1|1].add += tmp;
92 tree[id<<1].minn += tmp;tree[id<<1|1].minn += tmp;
93 tree[id<<1].maxn +=tmp;tree[id<<1|1].maxn += tmp;
94 tree[id<<1].sum += (tree[id<<1].r-tree[id<<1].l+1)*tmp;
95 tree[id<<1|1].sum += (tree[id<<1|1].r - tree[id<<1|1].l+1)*tmp;
96 tree[id].add = 0;
97 }
98 }