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
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define maxn 8001
int c[maxn << 3], cnt[maxn], l[maxn], r[maxn], v[maxn], ls[maxn << 2];
void pushdown(int o, int l, int r){
if(l == r || c[o] == -1) return;
c[o << 1] = c[o << 1 | 1] = c[o];
c[o] = -1;
}
void add(int o, int l, int r, int L, int R, int v){
pushdown(o, l, r);
if(l >= L && r <= R){
c[o] = v;
return;
}
int mid = l + r >> 1;
if(mid >= L) add(o << 1, l, mid, L, R, v);
if(mid < R) add(o << 1 | 1, mid + 1, r, L, R, v);
}
int query(int o, int l, int r, int id){
if(l == r) return c[o];
pushdown(o, l, r);
int mid = l + r >> 1;
if(id <= mid) return query(o << 1, l, mid, id);
else return query(o << 1 | 1, mid + 1, r, id);
}
int main(){
int n, x, y;
while(scanf("%d", &n) != EOF){
memset(c, -1, sizeof(c));
memset(cnt, 0, sizeof(cnt));
int tot = 0;
for(int i = 1; i <= n; ++i){
scanf("%d %d %d", &l[i], &r[i], &v[i]);
ls[++tot] = ++l[i];
ls[++tot] = r[i];
}
sort(ls + 1, ls + 1 + tot);
int num = unique(ls + 1, ls + 1 + tot) - ls;
int m = num;
for(int i = 2; i < num; ++i){
if(ls[i] - ls[i - 1] > 1){
ls[m++] = ls[i - 1] + 1;
}
}
sort(ls + 1, ls + m);
for(int i = 1; i <= n; ++i){
x = lower_bound(ls + 1, ls + m, l[i]) - ls;
y = lower_bound(ls + 1, ls + m, r[i]) - ls;
add(1, 1, m, x, y, v[i]);
}
x = query(1, 1, m, 1);
for(int i = 2; i <= m; ++i){
y = query(1, 1, m, i);
if(x != y){
if(x != -1) cnt[x]++;
x = y;
}
}
if(x != -1) cnt[x]++;
for(int i = 0; i <= 8000; ++i){
if(cnt[i] != 0){
printf("%d %d\n", i, cnt[i]);
}
}
puts("");
}
}
/*
题意:
按顺序对不同区间刷不同颜色,问最后整个区间有多少个颜色段。
思路:
线段树区间修改区间查询。需要考虑的是区间长度未知,需要离散化一下,离散的时候一定注意
如果差值大于2的情况不要让它们离散后连续了,比如[1,2],[4,5]很可能离散成[1,2],[3,4],这样会导致答案错误。
*/