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
Author: Standlove
Source: ZOJ Monthly, May 2003
#include <bits/stdc++.h>
using namespace std;
const int mn = 8005;
struct node
{
int l, r, col;
} t[8 * mn];
int col[mn], sum[mn];
void build(int i, int l, int r)
{
t[i].l = l, t[i].r = r;
t[i].col = -1;
if (l == r)
return;
int m = (l + r) / 2;
build(2 * i, l, m);
build(2 * i + 1, m + 1, r);
return;
}
void pushdown(int i, int l, int r, int m)
{
t[2 * i].col = t[2 * i + 1].col = t[i].col;
t[i].col = -1;
return;
}
void update(int i, int a, int b, int c)
{
int l = t[i].l, r = t[i].r;
int m = (l + r) / 2;
if (l == a && b == r)
{
t[i].col = c; /// 这段区间颜色更新为c
return;
}
if (t[i].col != -1)
pushdown(i, l, r, m);
if (b <= m)
update(2 * i, a, b, c);
else if (a > m)
update(2 * i + 1, a, b, c);
else
{
update(2 * i, a, m, c);
update(2 * i + 1, m + 1, b, c);
}
return;
}
void query(int i, int l, int r)
{
int m = (l + r) / 2;
if (l == r)
{
col[l] = t[i].col; // 每个长度为1的区间的颜色
return;
}
if (t[i].col != -1)
pushdown(i, l, r, m);
query(2 * i, l, m);
query(2 * i + 1, m + 1, r);
return;
}
int main()
{
int N;
while (~scanf("%d", &N))
{
build(1, 1, 8000);
while (N--)
{
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
update(1, a + 1, b, c); /// 将端点转化为区间
}
memset(sum, 0, sizeof sum);
memset(col, -1, sizeof col); // 记录各节点颜色
query(1, 1, 8000);
// for (int i = 1; i <= 8000; i++)
// if (col[i] != -1)
// cout<< i <<' '<<col[i]<<endl;
for (int i = 1; i <= 8000; i++)
if (col[i] != -1 && col[i] != col[i - 1])
sum[col[i]]++; // 该颜色区域++
for (int i = 0; i <= 8000; i++)
if (sum[i])
printf("%d %d\n", i, sum[i]);
printf("\n");
}
return 0;
}