Count the Colors (线段树区间染色)
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,r] 染色为 i,进行m次操作。后面染得可以覆盖前面染得。最后询问可见的连续颜色段有哪些。
思路:用线段树做,直接把tree[]和lazy[]合并来进行维护,开始建一颗空树,直接nmemset(tree,0,sizeof(tree))。然后逐个更新区间的值,标记lazy直接打在tree上,全部插入完后,查询一次,将lazy标记down到最下面,其中在查询过程中如果l==r存一下当前节点的color,最后存出来的数组就是按照从左到右的顺序来的。
代码:
#include <iostream>
#include <algorithm>
#include <string.h>
#define mid (left+right)/2
#define lson node*2,left,mid
#define rson node*2+1,mid+1,right
using namespace std;
const int maxn = 8005;
int tree[maxn*8];
int color[maxn*4];
int cnt = 0;
int num[maxn*4];
void down( int node )
{
if ( tree[node] ) {
tree[node*2] = tree[node*2+1] = tree[node];
tree[node] = 0;
}
}
void update( int node, int left, int right, int L, int R, int date )
{
if ( left>=L && right<=R ) {
tree[node] = date;
return ;
}
down(node);
if ( L<=mid ) {
update(lson,L,R,date);
}
if ( R>mid ) {
update(rson,L,R,date);
}
}
void query( int node, int left, int right )
{
if ( left==right ) {
color[cnt++] = tree[node]; // 在这个地方存,是按照最后一层从左到右的顺序来的
return ;
}
down(node);
query(lson);
query(rson);
}
int main()
{
int x,y,c,n,i,j;
while ( cin>>n ) {
cnt = 0;
memset(tree,0,sizeof(tree));
for ( int i=0; i<n; i++ ) {
cin >> x >> y >> c;
x ++;
c ++;
update(1,1,8005,x,y,c);
}
query(1,1,8005);
memset(num,0,sizeof(num));
for ( i=0; i<cnt; ) {
if ( color[i]==0 ) {
i ++;
continue ;
}
num[color[i]] ++;
for ( j=i+1; j<cnt; j++ ) {
if ( color[j]!=color[i]||color[j]==0 ) {
break ;
}
}
i = j;
}
for ( int i=1; i<=8005; i++ ) {
if ( num[i] ) {
cout << i-1 << " " << num[i] << endl;
}
}
cout << endl;
}
return 0;
}