CodeForces295A Greg and Array

CodeForces295A Greg and Array_第1张图片
![图片2.PNG](http://upload-images.jianshu.io/upload_images/2245939-e23f41ef9658f7d0.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

题目大意:给定一个序列, 给出m种操作,在每种操作中, l, r, d表示将区间[l, r]的所有值加d.之后的k个操作中,x, y表示该次将第x种操作到第y种操作都执行一次, 问经所有操作之后序列中每个元素的值。

这道题显然就是区间更新, 单点查询, 用线段树可以完成。
问题是有的操作需反复执行,如果直接一个一个更新,肯定超时。
事实上,k个操作相当于将之前m个操作中指定区间的操作的d值更新,可以将操作也用线段树维护,看每个操作的d值一共加了几次(一共需要执行多少次),然后即可求出最终的序列。

参考代码:

#include 
#include 
using namespace std;
typedef long long ll;
const int N = 1e5+10; 

ll a[N], b[N];
ll kk[N];
struct node {
    int left, right;
    ll max;
    ll lazy;
} e[N * 4];

struct op {
    int left, right;
    ll val;
} op[N];

void push_up(int p) {
    e[p].max = max(e[p*2].max, e[p*2+1].max);
}

void push_down(int p) {
    if (e[p].lazy != 0) {
        e[p*2].lazy += e[p].lazy;
        e[p*2].max += e[p].lazy;

        e[p*2+1].lazy += e[p].lazy;
        e[p*2+1].max += e[p].lazy;
        
        e[p].lazy = 0;
    }
}

void build(int p, int l, int r, ll a[]) {
    e[p].left = l;
    e[p].right = r;
    e[p].lazy = 0;

    if (l == r) {
        e[p].max = a[l];
    }

    else {
        int mid = (l + r) / 2;
        build(p*2, l, mid, a);
        build(p*2+1, mid+1, r, a);
        push_up(p);
    }
}

void update(int p, int l, int r, ll val) {
    if (l <= e[p].left && e[p].right <= r) {
        e[p].lazy += val;
        e[p].max += val;
    }
    else {
        push_down(p);
        int mid = (e[p].left + e[p].right) / 2;
        if (l <= mid) update(p*2, l, r, val);
        if (r > mid) update(p*2+1, l, r, val);
        push_up(p);
    }
}

ll query_max(int p, int l, int r) {
    if (l <= e[p].left && e[p].right <= r) {
        return e[p].max;
    }
    int mid = (e[p].left + e[p].right) / 2;
    push_down(p);
    ll ans = 0;
    if (l <= mid) ans = max(ans, query_max(p*2, l, r));
    if (r > mid) ans = max(ans, query_max(p*2+1, l, r));
    return ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int n, m, k;
    cin >> n >> m >> k;
    for (int i = 1;i <= n;++i) cin >> a[i];
    int l, r, d;
    for (int i = 1;i <= m;++i) {
        cin >> op[i].left >> op[i].right >> op[i].val;  
    }
    for (int i = 1;i <= m;++i) {
        kk[i] = 0;
    }
    int x, y;
    build(1, 1, m, kk);
    for (int i = 1;i <= k;++i) {
        cin >> x >> y;
        update(1, x, y, 1);
    }
    for (int i = 1;i <= m;++i) {
        kk[i] = query_max(1, i, i);
        op[i].val = op[i].val * kk[i];
    }
    build(1, 1, n, a);
    for (int i = 1;i <= m;++i) {
        update(1, op[i].left, op[i].right, op[i].val);
    }
    for (int i = 1;i <= n;++i) {
        b[i] = query_max(1, i, i);
    }
    for (int i = 1;i <= n;++i) {
        if (i > 1) cout << " "; 
        cout << b[i];
    }
    cout << endl;
    return 0;
}

你可能感兴趣的:(CodeForces295A Greg and Array)