Codeforces915E Physical Education Lessons (珂朵莉树)

题目链接: Physical Education Lessons

大致题意

给定一个长度为 n n n 01 01 01序列, 有两种操作: 把区间 [ l , r ] [l, r] [l,r]全部变为 1 1 1, 或把区间 [ l , r ] [l, r] [l,r]全部变为 0 0 0.

每次操作结束后, 输出序列中 1 1 1的个数.

解题思路

珂朵莉树

这不是珂朵莉树板子题吗? 我们只需要实现珂朵莉树的区间推平即可.

值得一提的是, 每次的查询, 我们可以通过维护一个变量 s u m sum sum的方式来做到 O ( 1 ) O(1) O(1)查询.

否则如果每次遍历完整个set的话, 会超时.


➡️线段树题解点这里⬅️


AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
struct node {
    
    
	int l, r; mutable ll v;
	bool operator< (const node& t) const {
    
     return l < t.l; }
}; set<node> st;
int sum;
auto split(int x) {
    
    
	auto it = st.lower_bound({
    
     x, 0, 0 });
	if (it != st.end() and it->l == x) return it;
	--it;
	auto [l, r, v] = *it;
	st.erase(it); st.insert({
    
     l, x - 1, v });
	return st.insert({
    
     x, r, v }).first;
}

void assign(int l, int r, int c) {
    
    
	auto R = split(r + 1), L = split(l);
	for (auto it = L; it != R; ++it) {
    
    
		if (it->v == 1) sum -= it->r - it->l + 1;
	}
	st.erase(L, R); st.insert({
    
     l, r, c });
	if (c) sum += r - l + 1;
}
int main()
{
    
    
	int n, m; cin >> n >> m;
	st.insert({
    
     1, n, 1 });
	sum = n;
	rep(i, m) {
    
    
		int l, r, tp; scanf("%d %d %d", &l, &r, &tp);
		assign(l, r, tp - 1);
		printf("%d\n", sum);
	}

    return 0;
}

END

猜你喜欢

转载自blog.csdn.net/weixin_45799835/article/details/121340646