线段树,区间更新

July 3, 2013
Data Structure

把一个区间内的值全部修改为一个确定值; 计算某个区间内的最大值,最小值,和。


#include <cstdio>
#include <algorithm>
#include <cstdlib>
using namespace std;
#define INF 0x7f7f7f7f
#define Max 600000
long long a[Max], setv[Max], minv[Max], maxv[Max], sumv[Max], _max, _min, _sum, v;
int y1,y2;
bool flagv[Max];
inline void maintain(int o, int L, int R) {
    if (flagv[o]) minv[o] = maxv[o] = setv[o], sumv[o] = (R-L+1)*setv[o];
    else if (R > L) minv[o] = min(minv[o*2], minv[o*2+1]), maxv[o] = max(maxv[o*2], maxv[o*2+1]),
        sumv[o] = sumv[o*2] + sumv[o*2+1];
}
void build(int o, int L, int R) {
    if (L == R) scanf("%lld", a+o), minv[o] = maxv[o] = sumv[o] = setv[o] = a[o];
    else {int M = L + (R-L)/2; build(o<<1, L, M), build(o*2+1, M+1, R), maintain(o, L, R);}
    flagv[o] = false;
}
inline void pushdown(int o) {
    if (flagv[o]) setv[o<<1] = setv[o<<1|1] = setv[o], flagv[o<<1] = flagv[o<<1|1] = true, flagv[o] = false;
}
void update(int o, int L, int R) {
    if (y1 <= L && y2 >= R) setv[o] = v, flagv[o] = true;
    else {
        int M = L + (R-L)/2; pushdown(o); if (y1 <= M) update(o<<1, L, M); else maintain(o<<1, L, M);
        if (y2 > M) update(o<<1|1, M+1, R); else maintain(o<<1|1, M+1, R);
    }
    maintain(o, L, R);
}
void query(int o, int L, int R) {
    if (flagv[o]) _sum += setv[o]*(min(y2, R) - max(y1, L) + 1), _min = min(_min, setv[o]), 
        _max = max(_max, setv[o]);
    else if (y1 <= L && y2 >= R) _sum += sumv[o], _min = min(_min, minv[o]), _max = max(_max, maxv[o]);
    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);}
}
int main(void) {
    freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
    int n, m; scanf("%d%d", &n, &m); build(1, 1, n);
    while (m--) {
        char ch; scanf("\n%c", &ch);
        if (ch == 'Q') scanf("%d%d", &y1, &y2), _sum = 0, _max = -INF, _min = INF, 
            query(1, 1, n), printf("%lld %lld %lld\n", _sum, _max, _min);
        else scanf("%d%d%lld", &y1, &y2, &v), update(1, 1, n);
    }
    return 0;
}

。。

comments powered by Disqus