先贴下题
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
。。。因为没看懂题WA了十几发,是我英语太差了。。
注意标黄的几句话:
1、涂的是线段,并且不包含端点(这个想要看出来可能还要结合样例。)
例如给定 1 2 5, 4 5 1
1涂色的地方 2 3 4 涂色的地方5
就是 给区间[1,2], [4,5] 涂色,而不是给1 2 4 5这四个数字涂色。
2、是在一条长为8000的线段上涂色,给的n只是让你去涂的有色线段的条数。
因为有:
Painting some colored segments on a line。
equal to the number of colored segments。
All the numbers are in the range [0, 8000], and they are all integers.
(正是因为线段长度为8000,当你把n作为更新的区间的右端点时,会发生RE或Segmentation Fault,因为涂色区间会超过n)
思路
虽然题目给的是开区间,但我们可以通过使左端点+1的方式使开区间涂色变成按点涂色。(把每个点和两点之间都当成一个涂色区域)
例:
给定 1 2 4,按题意是1涂色2, 我们使左端点++, 变成1 2,
给定1 2 4,2 3 5 我们改成1 2 3 4,中间隔了一个3,并没有改变相对的涂色区间。
于是,可以在遍历查询时记录上一个点的颜色代号,与当前点的颜色代号比较如果不同,当前点颜色的段数+1。
直接在输入的时候更新,不需要建树。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>#define N 8010int lc;
//num[i]记录节点的颜色代码(若存在),sum[i]记录代码i的颜色的段数
int num[4 * N], sum[N+1];void pushdown(int t)
{
if(num[t] > -1){
int lt = t << 1, rt = t << 1 | 1;num[lt] = num[t];num[rt] = num[t];num[t] = -1;}
}void update(int t, int l, int r, int pl, int pr, int val)
{
if(pl <= l && r <= pr){
num[t] = val;}else{
if(num[t] > -1){
pushdown(t);}int mid = (l + r) >> 1;if(pl <= mid){
update(t << 1, l, mid, pl,pr, val);}if(pr > mid){
update(t << 1 | 1, mid + 1, r, pl, pr, val);}}
}void query(int t, int l, int r)
{
if(l == r){
if(num[t] != -1 && num[t] != lc){
sum[num[t]]++;}lc = num[t];}else{
pushdown(t);int mid = (l + r) >> 1;query(t << 1, l, mid);query(t << 1 | 1, mid + 1, r);}
}int main()
{
int n, pl, pr, val;for(;scanf("%d", &n) != EOF;){
memset(num, -1, sizeof(num));memset(sum, 0, sizeof(sum));for(int i = 1;i <= n;i++){
scanf("%d%d%d", &pl, &pr, &val);pl++;update(1, 1,8000, pl, pr, val);}lc = -1;query(1, 1, 8000);for(int i = 0;i <= 8000;i++){
if(sum[i]!= 0){
printf("%d %d\n", i, sum[i]);}}printf("\n");}return 0;
}