ZOJ 1610 Count the Colors(线段树)

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



题意:

多组输入

给一个长度为8000的木板,求n次操作后,能看到哪些颜色,和该种颜色出现次数,连续出现算一次。

第一行 ,一个n表示染色次数

接下来n行每次给a,b,c,表示a点到b点内的区间 染成c色。


思路:

看了下别人的题解,O(n^2)竟然都过了。

这里采用线段树优化一下。

注意给的数据是点,染色是区间,所以可以令左边界+1 或 右边界-1。0+1比8000-1,看着爽我选择前者。

染色过程,详见代码。

最后答案的统计,可以开个last,记录前一个区间的颜色,因为线段树是先访问左儿子所以是从左到右顺序遍历。

每当遇到一个与前一个区间颜色不同的就使该颜色所在区间答案+1(类似桶排)


详见代码,初学线段树,代码较丑请多见谅,反正也没人看 (ಥ_ಥ)  

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define For(a,b,c) for(int a = b; a <= c; a++)
#define mem(a,b) memset(a,b,sizeof(a))
#define lson rt<<1 , l, m
#define rson rt<<1|1, m+1, r
#define ll long long

int N, last;
int col[32005], ans[8005];

void pushdown(int rt)
{
    if(col[rt] == -1) return;
    col[rt<<1] = col[rt];
    col[rt<<1|1] = col[rt];
    col[rt] = -1;
}

void update(int rt, int l, int r, int ql, int qr, int num)
{
    if(ql <= l && r <= qr)
    {
        col[rt] = num;
        return;
    }
    pushdown(rt);
    int m = (l+r)>>1;
    if(ql <= m) update(lson,ql,qr,num);
    if(qr > m) update(rson,ql,qr,num);
}

void Query(int rt, int l, int r, int ql, int qr)
{
    if(l == r)
    {
        if(col[rt] == -1)
        {
            last = col[rt];//这个忘记加了 wa了一发 ORZ
            return;
        }
        if(col[rt] != last) ans[col[rt]]++;
        last = col[rt];
        return;
    }
    pushdown(rt);
    int m = (l+r)>>1;
    if(ql <= m) Query(lson,ql,qr);
    if(qr > m) Query(rson,ql,qr);
}

int main()
{
    int l, r, a;
    while(~scanf("%d",&N))
    {
        mem(col,-1);
        mem(ans,0);
        last = -1;
        For(i,1,N)
        {
            scanf("%d%d%d",&l,&r,&a);
            update(1,1,8000,l+1,r,a);
        }
        Query(1,1,8000,1,8000);
        For(i,0,8000) if(ans[i]) printf("%d %d\n",i,ans[i]);
        printf("\n");
    }
    return 0;
}

### 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]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值