环博!

· · 题解

T3,考场没仔细想,好题。

思路

此时我们就解决了链的问题,于是对于存在 0 的询问就都解决了。

ps:其实我觉得这道题可以有一个保证询问区间 \nexists i \in [l, r], a_i = 0 的特殊性质的。

得到这个结论后直接转换为链情况,线段树维护区间内非最小值连续段贡献和即可,具体见代码。

code

由于直接视最小值为分界点,实际实现时不需对存在 0 的情况额外处理。

#include <bits/stdc++.h>
#define lson (u * 2)
#define rson (u * 2 + 1)
#define mid (l + r >> 1)
using namespace std;
const int N = 3e5 + 7;
int n, q, a[N];
int get(int x) {return (x % 2) ? x + 1 : x / 2;}
struct node {
    int mn, len;//最小值和长度
    int lenl, lenr;//左边区间和右边区间的长度。
    int ansj, anso;//合法奇长度和偶长度贡献
};
struct Segtree {
    node tr[N << 3];
    node chance(node a, node b) {//合并a,b的信息,钦定a为左部区间,b为右部区间
        node res;
        res.mn = min(a.mn, b.mn);
        res.len = a.len + b.len;
        if (a.mn < b.mn) {//最小值不等
            res.lenl = a.lenl, res.lenr = a.lenr + b.len;
            res.ansj = a.ansj, res.anso = a.anso;
        }
        else if (a.mn > b.mn) {
            res.lenl = a.len + b.lenl, res.lenr = b.lenr;
            res.ansj = b.ansj, res.anso = b.anso;
        }
        else {//最小值相等
            res.lenl = a.lenl, res.lenr = b.lenr;
            res.ansj = a.ansj + b.ansj;
            res.anso = a.anso + b.anso;
            if ((a.lenr + b.lenl) % 2)
                res.ansj += a.lenr + b.lenl + 1;
            else
                res.anso += (a.lenr + b.lenl) / 2;
        }
        return res;
    }
    void push_up(int u) {tr[u] = chance(tr[lson], tr[rson]);}//线段树板子
    void build_tree(int u, int l, int r) {
        if (l == r) {
            tr[u] = {a[l], 1, 0, 0, 0, 0};
            return;
        }
        build_tree(lson, l, mid);
        build_tree(rson, mid + 1, r);
        push_up(u);
    }
    void update(int u, int l, int r, int w, int x) {
        if (l == r) {
            tr[u].mn = x;
            return;
        }
        if (w <= mid)
            update(lson, l, mid, w, x);
        else
            update(rson, mid + 1, r, w, x);
        push_up(u);
    }
    node query(int u, int l, int r, int ml, int mr) {
        if (ml <= l && r <= mr)
            return tr[u];
        if (mr <= mid)
            return query(lson, l, mid, ml, mr);
        if (mid + 1 <= ml)
            return query(rson, mid + 1, r, ml, mr);
        node ls = query(lson, l, mid, ml, mr);
        node rs = query(rson, mid + 1, r, ml, mr);
        return chance(ls, rs);
    }
}tr;
int qry(int l, int r) {
    node ans = tr.query(1, 1, n, l, r);
    if (ans.mn && ans.len % 2)//注意判奇环情况
        return ans.len;
    return ans.ansj + ans.anso + get(ans.lenl + ans.lenr);
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n >> q;
    for (int i = 1; i <= n; i ++)
        cin >> a[i];
    tr.build_tree(1, 1, n);
    while (q --) {
        int op, x, y;
        cin >> op >> x >> y;
        if (op == 1)
            tr.update(1, 1, n, x, y);
        if (op == 2)
            cout << qry(x, y) << '\n';
    }
    return 0;
}

有地方不懂可以私信问喵。