Count the Colors(线段树)

题目链接: Count the Colors

本题在vjudge里没法提交, 所以给出ZOJ的链接.

大致题意

给定n个区间l, r和颜色c, 每次给[l, r]涂上c这个颜色. 后面的涂色会覆盖之前的涂色.

最后要求输出区间[0, 8000]中每种颜色及其出现的次数, 如果该颜色没有出现过则不输出.

解题思路

还是线段树的区间染色问题, 与Mayor‘s posters思路基本相同.

本题需要注意的地方是: 建树的区间是固定的[0, 8000], 给定的n是操作次数.

我查阅了网上的很多代码, 我发现网上别的代码的查询函数都写的不太理想, 都是查阅到树的叶子结点才进行统计和返回. 查询的复杂度硬生生写成了O(nlogn). 因此这里提供一种我统计出现次数的查询方式, 希望能够帮到大家!

AC代码

#include <bits/stdc++.h>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
using namespace std;
typedef long long ll;
const int N = 1E4 + 10;
int cou[N];
struct node {
    int l, r;
    int lazy;
}t[N << 2];
void pushdown(node& op, int lazy) { op.lazy = lazy; }
void pushdown(int x) {
    if (!t[x].lazy) return; 
    pushdown(t[x << 1], t[x].lazy), pushdown(t[x << 1 | 1], t[x].lazy);
    t[x].lazy = 0;
}

void build(int l, int r, int x = 1) {
	t[x] = { l, r, 0 };
    if (l == r) return;
    int mid = l + r >> 1;
    build(l, mid, x << 1), build(mid + 1, r, x << 1 | 1);
}

void modify(int l, int r, int c, int x = 1) {
    if (l <= t[x].l && r >= t[x].r) { pushdown(t[x], c); return; }
    pushdown(x);
    int mid = t[x].l + t[x].r >> 1;
    if (l <= mid) modify(l, r, c, x << 1);
    if (r > mid) modify(l, r, c, x << 1 | 1);
}

int last = 0; //表示上一次碰到的颜色, 记得当遍历叶子结点时没有颜色的时候也要记录.
void ask(int x = 1) {
    if (last != t[x].lazy) cou[t[x].lazy]++;
    if (t[x].lazy || t[x].l == t[x].r) { last = t[x].lazy; return; }
    ask(x << 1), ask(x << 1 | 1);
}
int main()
{
    int n;
    while (~scanf("%d", &n)) {
        build(1, 8010); last = 0;  
        memset(cou, 0, sizeof cou);
        rep(i, n) {
            int l, r, c; scanf("%d %d %d", &l, &r, &c);
            modify(l + 1, r, c + 1); //这里是为了让建树区间下标从1开始, 涂色记录也从1开始
        }
        ask();
        rep(i, 8010) if (cou[i]) printf("%d %d\n", i - 1, cou[i]);
        printf("\n");
    }
    return 0;
}

可能也是因为这个题没有多次查询吧. 只有8000的区间, 所以大佬们都懒得优化了.
只有我这个弱鸡怕吃T在优化 QAQ Orz

kuangbin线段树专题点这里!!!

END

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逍遥Fau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值