ZOJ1610_Count the Colors(线段树/成段更新)

本文介绍了一种使用线段树解决线段染色问题的方法。通过线段树实现区间更新,最终统计每种颜色在线段上的不连续区间数量。文章提供了完整的代码示例,并附带了手动随机数据的输入输出示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题报告

题意:

一根长度8000的线段上染色,求染完之后,每个颜色在线段上有多少个间断的区间。

思路:

区间问题用线段树,成段的更新区间,最后把所有的区间下压到叶子结点,统计叶子结点的颜色。

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;
int lz[32000],_hash[10000],color[10000],cnt;
void push_down(int rt)
{
    if(lz[rt])
    {
        lz[rt*2]=lz[rt*2+1]=lz[rt];
        lz[rt]=0;
    }
}
void update(int rt,int l,int r,int ql,int qr,int v)
{
    if(ql>r||qr<l)return ;
    if(ql<=l&&r<=qr)
    {
        lz[rt]=v;
        return ;
    }
    push_down(rt);
    int mid=(l+r)/2;
    update(rt*2,l,mid,ql,qr,v);
    update(rt*2+1,mid+1,r,ql,qr,v);
}
void bin(int rt,int l,int r)
{
    if(l==r)
    {
        color[cnt++]=lz[rt];
        return ;
    }
    push_down(rt);
    bin(rt*2,l,(l+r)/2);
    bin(rt*2+1,(l+r)/2+1,r);
}
int main()
{
    int n,m,i,j,ql,qr,a;
    while(~scanf("%d",&n))
    {
        cnt=0;
        memset(lz,0,sizeof(lz));
        memset(_hash,0,sizeof(_hash));
        m=8000;
        int cmax=-1;
        for(i=0; i<n; i++)
        {
            scanf("%d%d%d",&ql,&qr,&a);
            update(1,1,m,ql+1,qr,a+1);
        }
        bin(1,1,m);
        for(i=0; i<cnt;)
        {
            j=i+1;
            _hash[color[i]]++;
            while(color[j]==color[i]&&j<cnt)
                j++;
            i=j;
        }
        for(i=1; i<=m+1; i++)
        {
            if(_hash[i])
                printf("%d %d\n",i-1,_hash[i]);
        }
        printf("\n");
    }
    return 0;
}
附手动随机数据

input:
10
2 4 6 
4 6 2
1 9 3
4 6 2
1 20 3
2 4 3 
6 7 1
3 7 9
4 6 9
2 6 4
10
43 54 8000
323 4342 123
234 2332 321
2 6 23
54 546 1
2843 8888 8000
3000 8000 0
23 4329 9
923 2323 8
2390 3293 1
10
1 34 8000 
43 343 99
341 3414 8000
7999 8000 8000
344 345 1
434 3455 0
34 45 8000
43 56 45
56 64 0
898 4599 8000

output:
3 2
4 1
9 1

0 1
1 1
8 1
9 3
23 1

0 2
1 1
45 1
99 1
8000 5

Count the Colors

Time Limit: 2 Seconds      Memory Limit: 65536 KB

Painting some colored segments on a line, some previously painted segments may be covered by some the subsequent ones.

Your task is counting the segments of different colors you can see at last.


Input

The first line of each data set contains exactly one integer n, 1 <= n <= 8000, equal to the number of colored segments.

Each of the following n lines consists of exactly 3 nonnegative integers separated by single spaces:

x1 x2 c

x1 and x2 indicate the left endpoint and right endpoint of the segment, c indicates the color of the segment.

All the numbers are in the range [0, 8000], and they are all integers.

Input may contain several data set, process to the end of file.


Output

Each line of the output should contain a color index that can be seen from the top, following the count of the segments of this color, they should be printed according to the color index.

If some color can't be seen, you shouldn't print it.

Print a blank line after every dataset.


Sample Input

5
0 4 4
0 3 1
3 4 2
0 2 2
0 2 3
4
0 1 1
3 4 1
1 3 2
1 3 1
6
0 1 0
1 2 1
2 3 1
1 2 0
2 3 0
1 2 1


Sample Output

1 1
2 1
3 1

1 1

0 2
1 1



### ZOJ 1088 线段树 解题思路 #### 题目概述 ZOJ 1088 是一道涉及动态维护区间的经典问题。通常情况下,这类问题可以通过线段树来高效解决。题目可能涉及到对数组的区间修改以及单点查询或者区间查询。 --- #### 线段树的核心概念 线段树是一种基于分治思想的数据结构,能够快速处理区间上的各种操作,比如求和、最大值/最小值等。其基本原理如下: - **构建阶段**:通过递归方式将原数组划分为多个小区间,并存储在二叉树形式的节点中。 - **更新阶段**:当某一段区间被修改时,仅需沿着对应路径向下更新部分节点即可完成全局调整。 - **查询阶段**:利用懒惰标记(Lazy Propagation),可以在 $O(\log n)$ 时间复杂度内完成任意范围内的计算。 具体到本题,假设我们需要支持以下两种主要功能: 1. 对指定区间 `[L, R]` 执行某种操作(如增加固定数值 `val`); 2. 查询某一位置或特定区间的属性(如总和或其他统计量)。 以下是针对此场景设计的一种通用实现方案: --- #### 实现代码 (Python) ```python class SegmentTree: def __init__(self, size): self.size = size self.tree_sum = [0] * (4 * size) # 存储区间和 self.lazy_add = [0] * (4 * size) # 延迟更新标志 def push_up(self, node): """ 更新父节点 """ self.tree_sum[node] = self.tree_sum[2*node+1] + self.tree_sum[2*node+2] def build_tree(self, node, start, end, array): """ 构建线段树 """ if start == end: # 到达叶节点 self.tree_sum[node] = array[start] return mid = (start + end) // 2 self.build_tree(2*node+1, start, mid, array) self.build_tree(2*node+2, mid+1, end, array) self.push_up(node) def update_range(self, node, start, end, l, r, val): """ 区间更新 [l,r], 加上 val """ if l <= start and end <= r: # 当前区间完全覆盖目标区间 self.tree_sum[node] += (end - start + 1) * val self.lazy_add[node] += val return mid = (start + end) // 2 if self.lazy_add[node]: # 下传延迟标记 self.lazy_add[2*node+1] += self.lazy_add[node] self.lazy_add[2*node+2] += self.lazy_add[node] self.tree_sum[2*node+1] += (mid - start + 1) * self.lazy_add[node] self.tree_sum[2*node+2] += (end - mid) * self.lazy_add[node] self.lazy_add[node] = 0 if l <= mid: self.update_range(2*node+1, start, mid, l, r, val) if r > mid: self.update_range(2*node+2, mid+1, end, l, r, val) self.push_up(node) def query_sum(self, node, start, end, l, r): """ 查询区间[l,r]的和 """ if l <= start and end <= r: # 完全匹配 return self.tree_sum[node] mid = (start + end) // 2 res = 0 if self.lazy_add[node]: self.lazy_add[2*node+1] += self.lazy_add[node] self.lazy_add[2*node+2] += self.lazy_add[node] self.tree_sum[2*node+1] += (mid - start + 1) * self.lazy_add[node] self.tree_sum[2*node+2] += (end - mid) * self.lazy_add[node] self.lazy_add[node] = 0 if l <= mid: res += self.query_sum(2*node+1, start, mid, l, r) if r > mid: res += self.query_sum(2*node+2, mid+1, end, l, r) return res def solve(): import sys input = sys.stdin.read data = input().split() N, Q = int(data[0]), int(data[1]) # 数组大小 和 操作数量 A = list(map(int, data[2:N+2])) # 初始化数组 st = SegmentTree(N) st.build_tree(0, 0, N-1, A) idx = N + 2 results = [] for _ in range(Q): op_type = data[idx]; idx += 1 L, R = map(int, data[idx:idx+2]); idx += 2 if op_type == 'Q': # 查询[L,R]的和 result = st.query_sum(0, 0, N-1, L-1, R-1) results.append(result) elif op_type == 'U': # 修改[L,R]+X X = int(data[idx]); idx += 1 st.update_range(0, 0, N-1, L-1, R-1, X) print("\n".join(map(str, results))) solve() ``` --- #### 关键点解析 1. **初始化与构建**:在线段树创建过程中,需要遍历输入数据并将其映射至对应的叶子节点[^1]。 2. **延迟传播机制**:为了优化性能,在执行批量更新时不立即作用于所有受影响区域,而是记录更改意图并通过后续访问逐步生效[^2]。 3. **时间复杂度分析**:由于每层最多只访问两个子树分支,因此无论是更新还是查询都维持在 $O(\log n)$ 范围内[^3]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值