ssl2644-线段树练习1【线段树】

正题


题意

一块长m的墙,有n个大小不同的盒子放在前面,求没有被挡住的墙的总长度
ssl


解题思路

用线段树,0表示有没被遮挡的,1表示完全被遮挡,-1表示有遮挡的和没遮挡的。然后记数。


代码

#include<cstdio>
using namespace std;
struct xjq{
    int l,r;
    bool cover;
}tree[400000];
int n,ll,rr,w,s;
void build(int x,int a,int b)//建树
{
    tree[x].l=a;
    tree[x].r=b;
    if (b-a==1) return;
    else
    {
        int m=(a+b)/2;
        build(x*2,a,m);
        build(x*2+1,m,b);
    }
}
void inster(int x,int a,int b)//插入
{
    if (tree[x].cover) return;
    if (tree[x].l==a && tree[x].r==b) //标记
    {
      tree[x].cover=true;return;
    }
    int m=(tree[x].r+tree[x].l)/2;
    if (b<=m) inster(x*2,a,b);
    else if (a>=m) inster(x*2+1,a,b);
    else
    {
        inster(x*2,a,m);
        inster(x*2+1,m,b);
    }
    return;
}
void find(int x)
{
    if (tree[x].cover)//完全被遮挡
    {
        s+=tree[x].r-tree[x].l;
        return;
    }
    if (tree[x].r-tree[x].l==1) return;
    else 
    {
      find(x*2);
      find(x*2+1);
      return;
    }
}
int main()
{
    scanf("%d",&w);
    scanf("%d",&n);
    build(1,1,w);
    for (int i=1;i<=n;i++)
    {
        scanf("%d%d",&ll,&rr);
        inster(1,ll,rr);
    }
    s=0;
    find(1);
    printf("%d",s);
}

猜你喜欢

转载自blog.csdn.net/mr_wuyongcong/article/details/80255478