SSL_2646 线段树练习题三

题意

在一条线上染上几种颜色,求这些颜色把这条线分为几段。

思路

这道题的插入算法和练习题二差不多,只不过统计的时候要改一下。

代码

#include<cstdio>
int n,m,x,y,ans,z,f;
struct tr{
    int b,e,cover;
}tree[400001];
void creat(int p,int l,int r)
{
    tree[p].b=l;
    tree[p].e=r;
    if (r-l>1)
    {
        int m=(l+r)>>1;
        creat(2*p,l,m);
        creat(2*p+1,m,r);
    }
}
void insert(int p,int l,int r,int c)
{
    if (tree[p].cover!=c)//如果颜色不重复才进行操作,下面的和练习题二的差不多,就不做解释了
    {
        int m=(tree[p].b+tree[p].e)>>1;
        if (tree[p].b==l&&tree[p].e==r) tree[p].cover=c;
        else
        {
            if (tree[p].cover>=0)
            {
                tree[p*2].cover=tree[p*2+1].cover=tree[p].cover;
                tree[p].cover=-1;
            }
            if (r<=m) insert(2*p,l,r,c);
            else if (l>=m) insert(2*p+1,l,r,c);
            else
            {
                insert(2*p,l,m,c);
                insert(2*p+1,m,r,c);
            }
        }
    }
}
void count(int p)
{
    if (tree[p].cover>=0) 
    {
        if (tree[p].cover!=f)//用f记录我们下一段的颜色,如果当前的和它不相同,我们就统计答案,并且更新f
        {
            ans++;
            f=tree[p].cover;
        }
        return;
    }
    if (tree[p].e-tree[p].b>1)//不是叶节点就访问子节点
    {
        count(p*2);
        count(p*2+1);
    }
}
void init()
{
    scanf("%d%d",&n,&m);
    creat(1,1,m);
    for (int i=1;i<=n;i++)
    {
        scanf("%d%d%d",&x,&y,&z);
        insert(1,x,y,z);
    }
}
int main()
{
    init();
    count(1);
    printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/ssl_hzb/article/details/80245939