线段树,只能AC第二个点,可以提供样例吗
查看原帖
线段树,只能AC第二个点,可以提供样例吗
1165449
Februrary楼主2024/3/14 00:01
#include <iostream>
using namespace std;

int n, m;
struct node {
    int w;      // 记录1的数量
    int L, R;
    int tag;    // 标记是否需要反转
} stree[400050];

void pushup(const int u) {
    stree[u].w = stree[2 * u].w + stree[2 * u + 1].w;
}

void maketag(const int u, int L, int R, int change_value) {
    if(change_value == 0) return;
    stree[u].tag = change_value;
    if(L == R) stree[u].w ^= stree[u].tag;
    else if(stree[u].tag){
        stree[u].w = R - L + 1 - stree[u].w;
    }
}

void push_down(const int u, int L, int R) {
    int M = (L + R) >> 1;
    maketag(2 * u, L, M, stree[u].tag);
    maketag(2 * u + 1, M + 1, R, stree[u].tag);
    stree[u].tag = 0;
}

bool inRange(int L, int R, int l, int r) {
    return (L >= l) && (R <= r);
}

bool outRange(int L, int R, int l, int r) {
    return (R < l) || (L > r);
}

void build(const int u, int L, int R) {
    if(L == R) {
        stree[u].w = 0;
        return;
    }
    else {
        int M = (L + R) >> 1;
        build(2 * u, L, M);
        build(2 * u + 1, M + 1, R);
        pushup(u);
    }

}


void update(const int u, int L, int R, int l, int r) {
    if(inRange(L, R, l, r)) {
        maketag(u, L, R, 1);
        return;
    }
    else if(!outRange(L, R, l, r)) {
        int M = (L + R) >> 1;
        push_down(u, L, R);
        update(2 * u, L, M, l, r);
        update(2 * u + 1, M + 1, R, l, r);
        pushup(u);
    }

}

long long query(const int u, int L, int R, int l, int r) {
    if(inRange(L, R, l, r)) {
        return stree[u].w;
    }
    else if(outRange(L, R, l, r)) {
        return 0;
    }
    else {
        int M = (L + R) >> 1;
        push_down(u, L, R);
        return query(2 * u, L, M, l, r) + query(2 * u + 1, M + 1, R, l, r);

    }
}


int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    // 其实这个初始化没什么意义
    build(1, 1, n);
    for(int i = 0; i < m; i++) {
        int op = 0, a = 0, b = 0;
        cin >> op >> a >> b;
        if(op == 0) {
            update(1, 1, n, a, b);

        }
        else {
            cout << query(1, 1, n, a, b) << endl;
        }
    }


    return 0;
}
2024/3/14 00:01
加载中...