线段树,区间更新

把一个区间内的值全部修改为一个确定值;

计算某个区间内的最大值,最小值,和。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstdlib>
 4 using namespace std;
 5 #define INF 0x7f7f7f7f
 6 #define Max 600000
 7 long long a[Max], setv[Max], minv[Max], maxv[Max], sumv[Max], _max, _min, _sum, v;
 8 int y1,y2;
 9 bool flagv[Max];
10 inline void maintain(int o, int L, int R) {
11     if (flagv[o]) minv[o] = maxv[o] = setv[o], sumv[o] = (R-L+1)*setv[o];
12     else if (R > L) minv[o] = min(minv[o*2], minv[o*2+1]), maxv[o] = max(maxv[o*2], maxv[o*2+1]),
13         sumv[o] = sumv[o*2] + sumv[o*2+1];
14 }
15 void build(int o, int L, int R) {
16     if (L == R) scanf("%lld", a+o), minv[o] = maxv[o] = sumv[o] = setv[o] = a[o];
17     else {int M = L + (R-L)/2; build(o<<1, L, M), build(o*2+1, M+1, R), maintain(o, L, R);}
18     flagv[o] = false;
19 }
20 inline void pushdown(int o) {
21     if (flagv[o]) setv[o<<1] = setv[o<<1|1] = setv[o], flagv[o<<1] = flagv[o<<1|1] = true, flagv[o] = false;
22 }
23 void update(int o, int L, int R) {
24     if (y1 <= L && y2 >= R) setv[o] = v, flagv[o] = true;
25     else {
26         int M = L + (R-L)/2; pushdown(o); if (y1 <= M) update(o<<1, L, M); else maintain(o<<1, L, M);
27         if (y2 > M) update(o<<1|1, M+1, R); else maintain(o<<1|1, M+1, R);
28     }
29     maintain(o, L, R);
30 }
31 void query(int o, int L, int R) {
32     if (flagv[o]) _sum += setv[o]*(min(y2, R) - max(y1, L) + 1), _min = min(_min, setv[o]), 
33         _max = max(_max, setv[o]);
34     else if (y1 <= L && y2 >= R) _sum += sumv[o], _min = min(_min, minv[o]), _max = max(_max, maxv[o]);
35     else {int M = L + (R-L)/2; if (y1 <= M) query(o<<1, L, M); if (y2 > M) query(o<<1|1, M+1, R);}
36 }
37 int main(void) {
38     freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
39     int n, m; scanf("%d%d", &n, &m); build(1, 1, n);
40     while (m--) {
41         char ch; scanf("\n%c", &ch);
42         if (ch == 'Q') scanf("%d%d", &y1, &y2), _sum = 0, _max = -INF, _min = INF, 
43             query(1, 1, n), printf("%lld %lld %lld\n", _sum, _max, _min);
44         else scanf("%d%d%lld", &y1, &y2, &v), update(1, 1, n);
45     }
46     return 0;
47 }

。。

posted on 2013-07-03 14:08  aries__liu  阅读(1465)  评论(0编辑  收藏  举报