51nod“省选”模测第二场 C 小朋友的笑话(线段树 set)

题意

题目链接

Sol

直接拿set维护\(li\)连续段。因为set内的区间互不相交,而且每个线段会被至多加入删除一次,所以复杂度是对的。

#include<bits/stdc++.h>
#define Pair pair<int, int>
#define MP make_pair
#define fi first
#define se second 
using namespace std;
const int MAXN = 1e6 + 10, INF = 2147483646;
inline int read() {
    char c = getchar(); int x = 0, f = 1; 
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M, s[MAXN], f[MAXN], ll[MAXN], rr[MAXN];
#define ls k << 1
#define rs k << 1 | 1
void update(int k) {
	s[k] = s[ls] + s[rs];
}
void ps(int k, int v) {
	if(v == 1) s[k] = rr[k] - ll[k] + 1;
	else s[k] = 0;
	f[k] = v;
}
void pushdown(int k) {
	if(f[k] == -1) return ;
	ps(ls, f[k]); ps(rs, f[k]);
	f[k] = -1;
}
void Build(int k, int l, int r) {
	ll[k] = l; rr[k] = r;
	if(l == r) return ;
	int mid = l + r >> 1;
	Build(ls, l, mid); 
	Build(rs, mid + 1, r);
}
void Mem(int k, int l, int r, int ql, int qr, int val) {
	if(ql > qr) return ;
	if(ql <= l && r <= qr) {ps(k, val); return ;}
	int mid = l + r >> 1;
	pushdown(k);
	if(ql <= mid) Mem(ls, l, mid, ql, qr, val);
	if(qr  > mid) Mem(rs, mid + 1, r, ql, qr, val);
	update(k);
}
int Query(int k, int l, int r, int ql, int qr) {
	if(ql > qr) return 0;
	int ans = 0;
	//cout << ans << '\n';
	if(ql <= l && r <= qr) return s[k]; 
	int mid = l + r >> 1;
	pushdown(k);
	if(ql <= mid) ans += Query(ls, l, mid, ql, qr);
	if(qr  > mid) ans += Query(rs, mid + 1, r, ql, qr);
	
	return ans;
}
set<Pair> S[MAXN];
#define sit set<Pair>::iterator 
void Add(int l, int r, int x) {
	int pl = l, pr = r;
    set<Pair> &s = S[x]; 
    sit it = s.lower_bound(MP(l, r));
    Mem(1, 1, N, l, r, 1);
    if(it != s.begin()) {
        it--;
        if(it -> se > r) {
        	Mem(1, 1, N, max(pl, it -> fi), min(pr, it -> se), 0);
		}
        if(it -> se >= l ) {
  
            l = min(l, it -> fi); r = max(r, it -> se);
            Mem(1, 1, N, max(pl, it -> fi), min(pr, it -> se), 0);
            s.erase(it++);
        }
    }
    it = s.lower_bound(MP(l, r));
    while((it -> se >= l && it -> se <= r) || (it -> fi >= l && it -> fi <= r)) {
        l = min(l, it -> fi); r = max(r, it -> se);
        Mem(1, 1, N, max(pl, it -> fi), min(pr, it -> se), 0);
        s.erase(it++);
    }
    s.insert(MP(l, r));
}
signed main() {
//	freopen("a.in", "r", stdin);
    N = read(); M = read();
    Build(1, 1, N);
    for(int i = 1; i <= N; i++) S[i].insert(MP(INF, INF)); 
    while(M--) {
        int opt = read(); 
        if(opt == 1) {
        	int xi = read(), val = read(), ki = read();
			int l = max(1, xi - ki), r = min(N, xi + ki);
            Add(l, r, val);
        } 
        else {

			int l = read(), r = read();
			printf("%d\n", Query(1, 1, N, l, r));
    	}
	}
    return 0;
}
上一篇:P1516 青蛙的约会


下一篇:dockerui私有仓库,Java五年工作经验面试题