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
分析
题意:在一条【0,8000】的线段上染色,每次把区间【a,b】染成c颜色。后面染上的颜色可能会覆盖之前的颜色。求染完后每种颜色在线段上有多少个间断的区间。
用端点表示会存在数据丢失的情况。所以用区间表示。如节点t表示的是[t-1,t]这一个区间的颜色。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int N = 1e4 + 10;
int top;
int sum[N<<2], color[N<<2];
int res[N];
void pushdown(int rt){
if(color[rt]!=-1){
color[rt << 1] = color[rt << 1 | 1] = color[rt];
color[rt] = -1;
}
}
void build(int rt,int l,int r){
color[rt] = -1;
if(l==r)
return;
int mid = (l + r) >> 1;
build(rt << 1, l, mid);
build(rt << 1 | 1, mid + 1, r);
}
void update(int rt, int l, int r, int A, int B, int val)
{
if(A<=l&&r<=B){
color[rt] = val;
return;
}
pushdown(rt);
int mid = (l + r) >> 1;
if(A<=mid)
update(rt << 1, l, mid, A, B, val);
if(B>mid)
update(rt << 1 | 1, mid + 1, r, A, B, val);
}
void query(int rt,int l,int r){
if(l==r){
sum[top++] = color[rt];//记录节点的颜色
return;
}
pushdown(rt);
int mid = (l + r) >> 1;
query(rt << 1, l, mid);
query(rt << 1 | 1, mid + 1, r);
}
int main()
{
int n,m=8000,j;
int x1, x2, c;
while (~scanf("%d", &n))
{
build(1, 1, m);
// memset(color, -1, sizeof(color));
memset(sum, 0, sizeof(sum));//要带头文件 cstring
memset(res, 0, sizeof(res));
for (int i = 0; i < n; i++)
{
scanf("%d%d%d", &x1, &x2, &c);
update(1, 1, m, x1+1, x2, c);
}
top = 0;
query(1, 1, m);
for (int i = 0; i < top;){
if(sum[i]==-1){
i++;
continue;
}
res[sum[i]]++;
for (j = i + 1; j < top; j++)
{
if(sum[j]!=sum[i]||sum[j]==-1)
break;
}
i = j;
}
for (int i = 0; i <= m;i++){
if(res[i])
printf("%d %d\n", i, res[i]);
}
puts("");
}
return 0;
}