P2801 教主的魔法 (線段樹)

題目

P2801 教主的魔法c++

解析

整天作水題
線段樹,第一問區間加很簡單
第二問能夠維護一個區間最大值和一個區間最小值,若C小於等於區間最小值,就加上區間長度,若C大於區間最大值,就加0
ps:求教指針線段樹,個人空間怎麼那麼大git

代碼

#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, m, num;
int a[N];
class tree {
    public :
        int mx, mn, sum;
        int lazy, len;
        tree *ls, *rs;
        tree() {
            sum = mx = mn = lazy = len = 0;
            ls = rs = NULL;
        }
} t[N];

template<class T>inline void read(T &x) {
    x = 0; int f = 0; char ch = getchar();
    while (!isdigit(ch)) f |= (ch == '-'), ch = getchar();
    while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
    x = f ? -x : x;
    return;
}

inline void pushup(tree *rt) {
    rt->mn = min(rt->ls->mn, rt->rs->mn);
    rt->mx = max(rt->ls->mx, rt->rs->mx);
}

void build(int l, int r, tree *rt) {
    rt->len = r - l + 1;
    if (l == r) {
        rt->mn = rt->mx = a[l];
        return;
    }
    rt->ls = &t[++num], rt->rs = &t[++num];
    int m = (l + r) >> 1;
    build(l, m, rt->ls), build(m + 1, r, rt->rs);
    pushup(rt); 
}

inline void pushdown(tree *rt) {
    if (rt->lazy) {
        rt->ls->mx += rt->lazy;
        rt->rs->mx += rt->lazy;
        rt->ls->mn += rt->lazy;
        rt->rs->mn += rt->lazy;
        rt->ls->lazy += rt->lazy;
        rt->rs->lazy += rt->lazy;
        rt->lazy = 0;
    }
}

void update(int L, int R, int c, int l, int r, tree *rt) {
    if (L <= l && r <= R) {
        rt->mn += c;
        rt->mx += c;
        rt->lazy += c;
        return;
    } 
    pushdown(rt);
    int m = (l + r) >> 1;
    if (L <= m) update(L, R, c, l, m, rt->ls);
    if (R > m) update(L, R, c, m + 1, r, rt->rs);
    pushup(rt);
}

int query(int L, int R, int c, int l, int r, tree *rt) {
    if (L <= l && r <= R && rt->mn >= c) return rt->len;
    if (L <= l && r <= R && rt->mx < c) return 0;
    pushdown(rt);
    int m = (l + r) >> 1, ans = 0;
    if (L <= m) ans += query(L, R, c, l, m, rt->ls);
    if (R > m) ans += query(L, R, c, m + 1, r, rt->rs);
    return ans;
}

int main() {
    read(n), read(m);
    for (int i = 1; i <= n; ++i) read(a[i]);
    tree *rt = new tree;
    build(1, n, rt);
    for (int i = 1, x, y, z; i <= m; ++i) {
        char c;
        cin >> c;
        read(x), read(y), read(z);
        if (c == 'M') 
            update(x, y, z, 1, n, rt);
        else 
            printf("%d\n", query(x, y, z, 1, n, rt));
    }
    delete rt;
    return 0;
}
相關文章
相關標籤/搜索