线段树

#include <cstdio>
#include <algorithm>
#define maxtnode 65540
#define lchild(nid) (nid*2)
#define rchild(nid) (nid*2+1)

using namespace std;

struct node
{
    int left, right, sum;
    bool tag;
};

node stree[maxtnode];

void push(int n)
{
    stree[n].sum = stree[lchild(n)].sum + stree[rchild(n)].sum;
}

void clear(const int p, const int left, const int right)
{
    if (stree[p].tag)
    {
        stree[p].sum = 0;
        if (left != right)
        {
            stree[lchild(p)].tag = true;
            stree[rchild(p)].tag = true;
        }
        stree[p].tag = false;
    }
}

void build(int n, int l, int r)
{
    stree[n].left = l;
    stree[n].right = r;
    stree[n].tag = false;
    if (l == r)
        stree[n].sum = 1;
    else
    {
        build(lchild(n), l, (r + l) / 2);
        build(rchild(n), (r + l) / 2 + 1, r);
        push(n);
    }
}

void modify(int n, int l, int r)
{
    clear(n, stree[n].left, stree[n].right);
    if (l <= stree[n].left && stree[n].right <= r)
    {
        stree[n].sum = 0;
        stree[lchild(n)].tag = true;
        stree[rchild(n)].tag = true;
    }
    else
    {
        int mid = (stree[n].left + stree[n].right) >> 1;
        if (l <= mid)
            modify(lchild(n), l, r);
        if (r > mid)
            modify(rchild(n), l, r);
        clear(lchild(n), l, mid);
        clear(rchild(n), mid + 1, r);
        push(n);
    }
}

int main(void)
{
    int l, m, a, b, i;
    scanf("%d%d", &l, &m);
    build(1, 1, l + 1);
    for (i = 0; i < m; ++i)
    {
        scanf("%d %d", &a, &b);
        modify(1, a + 1, b + 1);
    }
    printf("%d", stree[1].sum);
    return 0;
}

3 条评论

  • 1

信息

ID
1103
难度
4
分类
模拟 点击显示
标签
递交数
14316
已通过
6534
通过率
46%
被复制
55
上传者