算法1
区间修改的线段树
(线段树) $O(nlogn)$
#include <iostream>
#define lson u << 1
#define rson u << 1 | 1
using namespace std;
const int N = 10002;
int L, m;
struct node {
int l, r;
int val;
bool tag;
}t[N << 2];
void pushup(int u) {
t[u].val = t[lson].val + t[rson].val;
}
void pushdown(int u) {
if (t[u].tag) {
t[u].tag = false;
t[lson].tag = true;
t[rson].tag = true;
t[lson].val = 0;
t[rson].val = 0;
}
}
void build(int u, int l, int r) {
t[u] = {l, r};
if (l == r) {
t[u].val = 1;
t[u].tag = false;
return;
}
int mid = l + r >> 1;
build(lson, l, mid);
build(rson, mid + 1, r);
pushup(u);
}
void update(int u, int l, int r, int k) {
if (l <= t[u].l && t[u].r <= r) {
t[u].tag = true;
t[u].val = k;
return;
}
pushdown(u);
int mid = t[u].l + t[u].r >> 1;
if (l <= mid) update(lson, l, r, k);
if (r > mid) update(rson, l, r, k);
pushup(u);
}
int query(int u, int l, int r) {
if (l <= t[u].l && r >= t[u].r) return t[u].val;
int mid = t[u].l + t[u].r >> 1;
pushdown(u);
int ans1, ans2;
if (l <= mid) ans1 = query(lson, l, mid);
if (r > mid) ans2 = query(rson, mid + 1, r);
return ans1 + ans2;
}
int main(){
cin >> L >> m;
build(1, 1, L + 1);
for (int i = 1; i <= m; i ++) {
int x, y;
cin >> x >> y;
update(1, x+1, y+1, 0);
}
cout << query(1, 1, L + 1);
return 0;
}