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
题意: 第一个数字表示操作数,每次操作可以把格子[l+1, r]涂上w颜色,新涂的颜色会覆盖掉之前涂的颜色,题目中出现数字均为[0, 8000]范围中的整数,询问最后各不同颜色出现次数。如果[a, b]与[b+1, c]格子颜色相同,则该颜色算是出现了一次。
分析: 区间覆盖问题,用线段树维护区间和以及区间修改+单点查询,所有涂色操作结束后for循环+单点查询遍历一遍,统计不同颜色段出现次数即可。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int sum[8005<<2], lazy[8005<<2], mp[8005];
void push_down(int id, int ln, int rn)
{
if(lazy[id])
{
lazy[id<<1] = lazy[id];
lazy[id<<1|1] = lazy[id];
sum[id<<1] = lazy[id]*ln;
sum[id<<1|1] = lazy[id]*rn;
lazy[id] = 0;
}
}
void push_up(int id)
{
sum[id] = sum[id<<1]+sum[id<<1|1];
}
void build(int l, int r, int id)
{
sum[id] = lazy[id] = 0;
if(l == r)
return;
int m = l+r>>1;
build(l, m, id<<1), build(m+1, r, id<<1|1);
push_up(id);
}
void update(int L, int R, int C, int l, int r, int id)
{
if(L == l && R == r)
{
sum[id] = C*(r-l+1);
lazy[id] = C;
return;
}
int m = l+r>>1;
push_down(id, m-l+1, r-m);
if(R <= m)
update(L, R, C, l, m, id<<1);
else if(L >= m+1)
update(L, R, C, m+1, r, id<<1|1);
else
update(L, m, C, l, m, id<<1), update(m+1, R, C, m+1, r, id<<1|1);
push_up(id);
}
int query(int L, int l, int r, int id)//单点询问
{
if(l == r)
return sum[id];
int m = l+r>>1;
push_down(id, m-l+1, r-m);
if(L <= m)
return query(L, l, m, id<<1);
else
return query(L, m+1, r, id<<1|1);
}
signed main()
{
int m;
while(cin >> m)
{
// build(1, 8000, 1);
memset(sum, 0, sizeof sum);
memset(lazy, 0, sizeof lazy);
memset(mp, 0, sizeof mp);
for(int i = 1; i <= m; i++)
{
int l, r, c;
cin >> l >> r >> c;
l++;
c++;//颜色从1开始
update(l, r, c, 1, 8000, 1);
}
int last = query(1, 1, 8000, 1);
mp[last]++;
for(int i = 2; i <= 8000; i++)
{
int t = query(i, 1, 8000, 1);
if(t != last)
{
last = t;
mp[t]++;
}
}
for(int i = 1; i <= 8001; i++)
if(mp[i] != 0)
cout << i-1 << ' ' << mp[i] << endl;
cout << endl;
}
return 0;
}