线段树(线段染色)

1191 数轴染色

题目描述 Description

在一条数轴上有N个点,分别是1~N。一开始所有的点都被染成黑色。接着
我们进行M次操作,第i次操作将[Li,Ri]这些点染成白色。请输出每个操作执行后
剩余黑色点的个数。

输入描述 Input Description

输入一行为N和M。下面M行每行两个数Li、Ri

输出描述 Output Description

输出M行,为每次操作后剩余黑色点的个数。

样例输入 Sample Input

10 3
3 3
5 7
2 8

样例输出 Sample Output

9
6
3

数据范围及提示 Data Size & Hint

数据限制
对30%的数据有1<=N<=2000,1<=M<=2000
对100%数据有1<=Li<=Ri<=N<=200000,1<=M<=200000

这道题的lazy和value就不能累加因为这里是标记颜色,而不是求和;

#include <iostream>
#include <iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include <stdio.h>
#include <string.h>
#define rep(i , n) for(int i = 0 ; i < (n) ; i++)
using namespace std;
const int N = 1100009 ;
int ans = 0 , flag = 1;
int a[1000009] , b[1000009];

struct Node{
    int  l , r , val , lazy_tag ;
}tree[N * 4];

void build(int l , int r , int root)
{
    tree[root].l = l , tree[root].r = r ;
    tree[root].val = 0 , tree[root].lazy_tag = 0 ;
    if(l == r)
        return ;
    int mid = (l + r) >> 1 ;
    build(l , mid , root*2);
    build(mid + 1 , r , root*2+1);
}

void pushdown(int root)
{
    tree[root*2].lazy_tag = tree[root].lazy_tag;
    tree[root*2+1].lazy_tag = tree[root].lazy_tag ;

    tree[root * 2].val = (tree[root*2].r - tree[root*2].l+1)*tree[root].lazy_tag ;
    tree[root*2+1].val = (tree[root*2+1].r - tree[root*2+1].l+1)*tree[root].lazy_tag ;
    tree[root].lazy_tag = 0;
}
void update(int l  , int r ,int addval ,int root )
{
    if(tree[root].l >= l && tree[root].r <= r)
    {
        tree[root].lazy_tag = addval ; // 注意这道题不能用+= ,因为1就代表白色,再染一遍也是白色。
        tree[root].val = (tree[root].r - tree[root].l + 1) * addval ;
        return ;
    }
    if(tree[root].lazy_tag)
        pushdown(root);
    int mid = (tree[root].l + tree[root].r) >> 1;
    if(l <= mid)
        update(l , r, addval , root*2);
    if(r > mid)
        update(l , r, addval , root*2+1);
    tree[root].val = tree[root*2].val + tree[root*2+1].val ;
}

void  query(int l,int r  ,int root )
{
    if(tree[root].l >= l && tree[root].r <= r)
    {
        ans = tree[root].val ;
        return ;
    }
    if(tree[root].lazy_tag)
        pushdown(root);
    int mid = (tree[root].r + tree[root].l) >> 1 ;
    if(l <= mid)
        query(l , r , root*2);
    if(r > mid)
        query(l , r , root*2+1);

}



int main()
{
    int n , q ;
    while(~scanf("%d%d" , &n , &q))
    {
        build(1 , n , 1);
        for(int i = 0 ; i < q ; i++)
        {
            int l , r  , value = 1;
            scanf("%d%d" , &l ,&r);
            update(l , r , value , 1) ;
            query(1 , n , 1);
            cout << n - ans << endl ;
            ans = 0 ;
        }
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/nonames/p/11260163.html