P1047题解

· · 题解

其他题解都没有 O(n \log n) 做法,所以就有了这篇题解

非常明显的线段树。区间加,区间查询。

我们把 sum 设置为树的数量,初始为 1 。

因为这里面赋值是赋值为 0 ,所以把懒标记设为是否赋值,为 1 时把数量赋值为 0 。

其他的就是模版。

#include<bits/stdc++.h>
#define lc u<<1
#define rc u<<1|1
using namespace std;
struct node
{
    int l,r,sum,lazy;
}t[80010];
void build(int l,int r,int u)
{
    t[u].l=l;
    t[u].r=r;
    if(l==r)
    {
        t[u].sum=1;//sum为1
        return;
    }
    int mid=(l+r)/2;
    build(l,mid,lc);
    build(mid+1,r,rc);
    t[u].sum=t[lc].sum+t[rc].sum;
    return;
}
void push_down(int u)//下传
{
    if(t[u].lazy==1)//为1时赋值
    {
        t[lc].lazy=t[u].lazy;
        t[rc].lazy=t[u].lazy;
        t[lc].sum=0;
        t[rc].sum=0;
        t[u].lazy=0;
    }
}
void update(int l,int r,int u)//更新
{
    if(t[u].l>=l && t[u].r<=r)
    {
        t[u].sum=0;
        t[u].lazy=1;
        return;
    }
    push_down(u);
    int mid=(t[u].l+t[u].r)/2;
    if(l<=mid)
    {
        update(l,r,lc);
    }
    if(r>mid)
    {
        update(l,r,rc);
    }
    t[u].sum=t[lc].sum+t[rc].sum;
    return;
}
int find(int l,int r,int u)//查询
{
    push_down(u);
    if(t[u].l>=l && t[u].r<=r)
    {
        return t[u].sum;
    }
    int mid=(t[u].l+t[u].r)/2,ans=0;    
    if(l<=mid)
    {
        ans+=find(l,mid,lc);
    }
    if(r>mid)
    {
        ans+=find(mid+1,r,rc);
    }
    return ans;
}
int main()
{
    int l,m;
    cin>>l>>m;
    build(0,l,1);
    for(int i=1;i<=m;i++)
    {
        int l,r;
        cin>>l>>r;
        update(l,r,1);
    }
    cout<<find(0,l,1);
    return 0;
}