ZOJ - 1610 Count the Colors(线段树 - 区间更新)

题目链接:https://zoj.pintia.cn/problem-sets/91827364500/problems/91827365109

题意:给你n个被染了颜色的线段,后面的会覆盖前面的,输出可以看到的颜色以及这个颜色染了多少条线段。

思路:这一题和POJ2528那个贴海报那题很像,都是用的是线段树区间更新,但是这个要输出每种颜色一共染了多少条线段,所以连续的区间染上了同一种颜色只能算是一个区间。所以我们可以在query操作时加一个last表示上一个点的颜色,如果待查询的点的颜色和last相同,就不需要更新答案,就像这样

if(l==r)
{
    if(sum[rt]!=-1&&sum[rt]!=last) vis[sum[rt]]++;
    last=sum[rt];
    return ;
}

还有就是每次输入的是[x,y],但我们要更新的确是[x+1,y]。(虽然我不知道其他的大佬是怎么看出来的)其他的就和POJ2528几乎一样啦,都是用push_down函数把染色的区间推到最底层。具体的请看代码。

代码:

#include<set>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

#define LL long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn = 8000;

int sum[maxn<<2+7];

void push_down(int rt)
{
    if(sum[rt]!=-1)
    {
        sum[rt<<1]=sum[rt<<1|1]=sum[rt];
        sum[rt]=-1;
    }
}

void update(int L,int R,int color,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        sum[rt]=color;
        return ;
    }
    push_down(rt);
    int m=(l+r)>>1;
    if(L<=m) update(L,R,color,lson);
    if(R>m) update(L,R,color,rson);
}

int vis[maxn+7];
int last;
void query(int L,int R,int l,int r,int rt)
{
    if(l==r)
    {
        if(sum[rt]!=-1&&sum[rt]!=last) vis[sum[rt]]++;
        last=sum[rt];
        return ;
    }
    push_down(rt);
    int m=(l+r)>>1;
    if(L<=m) query(L,R,lson);
    if(R>m) query(L,R,rson);
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        memset(sum,-1,sizeof(sum));
        for(int i=1; i<=n; i++)
        {
            int x,y,c;
            scanf("%d%d%d",&x,&y,&c);
            update(x+1,y,c,0,maxn,1);
        }
        memset(vis,0,sizeof(vis));
        last=-1;
        query(0,maxn,0,maxn,1);
        for(int i=0; i<=maxn; i++) if(vis[i]) printf("%d %d\n",i,vis[i]);
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值