ZOJ 1610 Count the Colors 线段树区间修改

题意:
在一个区间为[0,8000]的布上染色,后染的颜色能覆盖前面的。
请问经过Q次染色后,每种颜色染的间断区间数目是多少。


分析:
区间覆盖问题容易联想到线段树的区间修改操作。
我个人喜欢区间从1开始,所以对所有的区间下标加了1。
注意:
题目的染色区间是把[A,B]染色,不是离散的点进行染色。

为了无缝染色,建树过程与普通的建树稍微有点区别,具体实现见代码。

#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 8000+5;
struct node{
   int left,right;
   int col;
};
int color[maxn],pre;

struct Tree{
   node tr[maxn*4];
   #define lch(u) (u<<1)
   #define rch(u) (u<<1|1)
   #define Mid (tr[u].left+tr[u].right)>>1

   void build(int u, int a, int b){
       tr[u].left = a; tr[u].right = b; tr[u].col = -1;
       if (a+1 == b) return;
       int mid = Mid;
       build(lch(u),a,mid);
       build(rch(u),mid,b);
   }

   void push_down(int u){
       if (tr[u].col <0) return;
       tr[lch(u)].col = tr[rch(u)].col = tr[u].col;
       tr[u].col = -2;
   }

   void update(int u, int a, int b, int c){
       if (a == b) return;
       if (tr[u].col == c) return;
       if (a<=tr[u].left && tr[u].right <= b) {
           tr[u].col = c;
           return;
       }

       push_down(u);
       int mid = Mid;
       if (b<=mid) update(lch(u),a,b,c);
       else if (a>mid) update(rch(u),a,b,c);
       else {
           update(lch(u),a,mid,c);
           update(rch(u),mid,b,c);
       }
       tr[u].col = -2;
   }

   void query(int u){
       if (tr[u].col == -1) { // no color
          pre = -1;
          return;
       }

       if (tr[u].col == -2) { // it means there are more than one color in this segment
           if (tr[u].left+1!=tr[u].right) {
              query(lch(u));
              query(rch(u));
           }
       }
       else {
           if (tr[u].col!=pre) { // pre records the color of the segment before u
               pre = tr[u].col;
               color[pre]++;
           }
       }
   }
}T;

int n;
int main(){
    while (scanf("%d",&n)==1){
        T.build(1,1,8001);

        int a,b,c;
        while (n--) {
            scanf("%d %d %d",&a,&b,&c);
            T.update(1,a+1,b+1,c);
        }

        memset(color,0,sizeof(color));
        pre = -1;
        T.query(1);

        for (int i=0; i<maxn; i++) if (color[i]) printf("%d %d\n",i,color[i]);
        printf("\n");
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值