Count the Colors(线段树之区间成段更新)

萌萌哒的传送门


这道题目是线段树区间成段更新的应用,我们只需在建立线段树时从原来的左右儿子不相连,改为相连即可以解决此类问题.


如从原来的[l,mid] , [mid + 1,r] 改为 [l,mid],[mid,r]即可;


/*********************
 * zoj1610           *
 * 线段树的区间成段更新 
 * 延迟标记           *
 *********************/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>

#define ls u << 1
#define rs u << 1 | 1
#define lson l, mid, u << 1
#define rson mid, r, u << 1 | 1
#define INF 0x3f3f3f3f

using namespace std;
typedef long long ll;
const int M = 8800;
int tmp[M << 2],a[M],to;

/*
 * 线段树的区间更新,需要注意此时的区间不再是点的更新,所以
 * 以[l,mid],[mid,r]来作为根的左右儿子,可以处理整段区间问题;
 */

struct Node {
    int u,v,c;
    void read() {
        scanf("%d %d %d",&u,&v,&c);
    }
} p[M];

struct Color{ //用来保存最后状态的区间染色情况;
    int l,r,c;
}color[M];

void pushdown(int u) {
    if(tmp[u] != -1) {
        tmp[ls] = tmp[rs] = tmp[u];
        tmp[u] = -1;
    }
}

void pushup(int u) {
    if(tmp[ls] == tmp[rs])
        tmp[u] = tmp[ls];
}

void update(int L,int R,int c,int l,int r,int u) {
    int mid = (l + r) >> 1;
    if(L <= l && R >= r) {
        tmp[u] = c;
    } else {
        pushdown(u);
        if(L < mid) update(L,R,c,lson);
        if(R > mid) update(L,R,c,rson);
        pushup(u);
    }
}

void query(int l,int r,int u) {
    int mid = (l + r) >> 1;
    if(tmp[u] != -1) {
        color[to].l = l;
        color[to].r = r;
        color[to++].c = tmp[u];
    } else {
        if(l == r - 1) return ;
        query(lson);
        query(rson);
    }
}

int main() {
    //freopen("in","r",stdin);
    int n;
    while(~scanf("%d",&n)) {
        memset(tmp,-1,sizeof(tmp));
        memset(a,0,sizeof(a));
        int L = M, R = -1,num = 0;
        for(int i = 0; i < n; i++) {
            p[i].read();
            L = min(L,p[i].u);
            R = max(R,p[i].v);
        }
        for(int i = 0; i < n; i++) {
            update(p[i].u,p[i].v,p[i].c,L,R,1);
        }
        to = 0;
        query(L,R,1);
        a[color[0].c]++;
        for(int i = 1; i < to; i++){
            if(color[i].l == color[i - 1].r && color[i].c == color[i - 1].c){
                //如果当前区间是衔接之间的区间且颜色又一致的话,则这两段区间同属一段;
                continue;
            }
            a[color[i].c]++; //否则为新的一段区间
        }
        for(int i = 0; i < M; i++){
            if(a[i]){
                printf("%d %d\n",i,a[i]);
            }
        }
        puts("");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值