根据提示我们要给长度为L的区间建立线段树,但是L很大,所以不能直接对L建树。
转化一下就是一共n个区间,最多2*n个点,所以我们可以使用较小的2*n个数来代替这些比较大的数而保证他们的相对大小不发生变化。然后我们就可以对长度为2*n的区间建立线段树了。
然后需要注意的一点是离散的线段树结点为[i,i],左儿子区间为[l,mid],右儿子区间为[mid+1,r]。
但是对于连续的区间线段树结点为[i,i+1],左儿子区间为[l,mid],右儿子区间为[mid,r]
然后按照线段树的方法做就Ok了。
#pragma warning(disable:4996) #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 100005; const int M = (N << 2) * 2; int l[M], r[M], lazy[M], num[M];//num为最大值 int a[N], b[N], c[2 * N], id[2 * N]; void pushUp(int i){ num[i] = max(num[i * 2], num[i * 2 + 1]); } void pushDowm(int i){ if (lazy[i] == 0)return; lazy[i * 2] = lazy[i]; lazy[i * 2 + 1] = lazy[i]; num[i * 2] = num[i * 2 + 1] = lazy[i]; lazy[i] = 0; } void build(int ll, int rr, int i){ l[i] = ll, r[i] = rr; if (ll + 1 == rr){ num[i] = 0; return; } int mid = (ll + rr) >> 1; build(ll, mid, 2 * i); build(mid, rr, 2 * i + 1); pushUp(i); } void update(int ll, int rr, int id, int i){ if (l[i] >= ll&&r[i] <= rr){ num[i] = id; lazy[i] = id; return; } if (lazy[i])pushDowm(i); int mid = (l[i] + r[i]) >> 1; if (rr <= mid)update(ll, rr, id, i * 2); else if (ll >= mid)update(ll, rr, id, i * 2 + 1); else{ update(ll, mid, id, i * 2); update(mid, rr, id, i * 2 + 1); } pushUp(i); } int query(int ll, int rr, int i){ if (ll <= l[i] && rr >= r[i]){ return num[i]; } if (lazy[i])pushDowm(i); int mid = (l[i] + r[i]) >> 1; if (rr <= mid)return query(ll, rr, i * 2); else if (ll >= mid)return query(ll, rr, i * 2 + 1); else return max(query(ll, mid, i * 2), query(mid, rr, i * 2 + 1)); } int main(){ int n, L; scanf("%d %d ", &n, &L); for (int i = 1; i <= n; i++){ scanf("%d %d", a + i, b + i); c[i] = a[i]; c[i + n] = b[i]; } sort(c + 1, c + 1 + 2 * n); int cnt = 0; for (int i = 1; i <= 2 * n; i++){ if (id[c[i]])continue; id[c[i]] = ++cnt; } build(1, cnt, 1); for (int i = 1; i <= n; i++){ int x = id[a[i]], y = id[b[i]]; update(x, y, i, 1); } memset(a, 0, sizeof a); for (int i = 1; i < cnt; i++){ a[query(i, i + 1, 1)] = 1; } int ans = 0; for (int i = 1; i <= n; i++){ ans += a[i]; } printf("%d\n", ans); return 0; }