【Codeforces 915E】 Physical Education Lessons

【题目链接】

          点击打开链接

【算法】

           线段树,注意数据量大,要动态开点

【代码】

          

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10000005;

int n,q,l,r,opt,size = 1,root = 1;
struct Node {
        int lc,rc,tag,sum;
} Tree[MAXN];

template <typename T> inline void read(T &x) {
        int f = 1; x = 0;
        char c = getchar();
        for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
        for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
        x *= f;
}
template <typename T> inline void write(T x) {
    if (x < 0) { putchar('-'); x = -x; }
    if (x > 9) write(x/10);
    putchar(x%10+'0');
}
template <typename T> inline void writeln(T x) {
    write(x);
    puts("");
}

inline void push_up(int root) {
        Tree[root].sum = Tree[Tree[root].lc].sum + Tree[Tree[root].rc].sum; 
}
inline void push_down(int l,int r,int root) {
        int mid = (l + r) >> 1;
        if (Tree[root].tag != -1) {
                if (!Tree[root].lc) Tree[root].lc = ++size;
                if (!Tree[root].rc) Tree[root].rc = ++size;
                Tree[Tree[root].lc].tag = Tree[Tree[root].rc].tag = Tree[root].tag;
                Tree[Tree[root].lc].sum = Tree[root].tag * (mid - l + 1);
                Tree[Tree[root].rc].sum = Tree[root].tag * (r - mid); 
                Tree[root].tag = -1;
        }
}
inline void modify(int &root,int l,int r,int ql,int qr,int val) {
        int mid;
        if (!root) root = ++size;
        if (l == ql && r == qr) {
                Tree[root].sum = val * (r - l + 1);
                Tree[root].tag = val;
                return;
        }
        push_down(l,r,root);
        mid = (l + r) >> 1;
        if (mid >= qr) modify(Tree[root].lc,l,mid,ql,qr,val);
        else if (mid + 1 <= ql) modify(Tree[root].rc,mid+1,r,ql,qr,val);
        else {
                modify(Tree[root].lc,l,mid,ql,mid,val);
                modify(Tree[root].rc,mid+1,r,mid+1,qr,val);
        }
        push_up(root);
}

int main() {
        
        read(n); read(q);
        while (q--) {
                read(l); read(r); read(opt);
                if (opt == 1) modify(root,1,n,l,r,1);
                else modify(root,1,n,l,r,0);    
                writeln(n - Tree[1].sum);
        } 
        
        return 0;
    
}
原文地址:https://www.cnblogs.com/evenbao/p/9196351.html