防止原来的区间太大(比如n的范围为1e9,询问的个数为1e5),此时我们就可以动态开点,防止普通线段树的空间过大导致MLE。
题目链接:E. Physical Education Lessons
区间查询,区间修改:
#include <bits/stdc++.h>
using namespace std;
const int N = 6e5*25; //(询问l, r最大个数*logn), 大概是这样
struct NODE {int l, r, lazy = -1, sum = 0;//为1代表非工作日的个数
} node[N];
int root, idx;
void pushup(int now) {node[now].sum = node[node[now].l].sum + node[node[now].r].sum;
}
void pushdown(int l, int r, int now) {int mid = l+r>>1;if(!node[now].l) node[now].l = ++idx;if(!node[now].r) node[now].r = ++idx;node[node[now].l].lazy = node[node[now].r].lazy = node[now].lazy;node[node[now].l].sum = node[now].lazy*(mid - l + 1);node[node[now].r].sum = node[now].lazy*(r - mid);node[now].lazy = -1;
}
void insert(int &now, int x, int y, int l, int r, int k) { //区间修改if(!now) now = ++idx;if(x<=l && y>=r) {node[now].sum = k*(r-l+1);node[now].lazy = k;return;}if(node[now].lazy!=-1) pushdown(l, r, now); //下放 int mid = l+r>>1;if(x<=mid) insert(node[now].l, x, y, l, mid, k);if(y>mid) insert(node[now].r, x, y, mid+1, r, k);pushup(now);
}
int query(int now, int x, int y, int l, int r) { //用法: query(root, l, r, 1, n)if(!now) return 0; //说明节点为空if(x<=l && y>=r) return node[now].sum; if(node[now].lazy!=-1) pushdown(l, r, now); //下放 int mid = l+r>>1, ans = 0;if(x<=mid) ans+=query(node[now].l, x, y, l, mid);if(y>mid) ans+=query(node[now].r, x, y, mid+1, r);return ans;
}
int main() {int n, q;scanf("%d%d", &n, &q);int l, r, op;while(q--) {scanf("%d%d%d", &l, &r, &op);if(op==1) insert(root, l, r, 1, n, op); //非工作日else insert(root, l, r, 1, n, 0); //工作日printf("%d\n",n-node[root].sum);
// printf("%d\n", n - query(root, 1, n, 1, n));}return 0;
}
单点修改:
//用法:change(root, x, 1, n, k) x为修改的点
void change(int &now, int x, int l, int r, int k){ //单点修改, 就不需要lazy了 if(!now) now = ++idx; //节点为空, 创建一个新结点 if(l == r){node[now].sum += k; //修改 return;}int mid = l+r>>1;if(x<=mid) change(node[now].l, x, l, mid, k);else change(node[now].r, x, mid+1, r, k);pushup(now);
}