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
题意:在给定区间上涂给定的颜色 后涂的会覆盖之前涂的 问涂完以后每种颜色各有多少块
思路:线段树 1.涂色是区间更新 遇到满足的区间就可以直接涂色覆盖
2.线段树的点是一个点是一个区间 而题目要求是两个点之间的涂色(详见下图)所以要将左区间端点+1就可以避免这个问题
3.本来还在想怎么记录涂过的颜色 然后数据量不大 直接循环一遍
4.可能会出现一个连续的区间被分开到两个节点 用last记录上一个被添加的颜色 同样就不再添加了
线段树的区间:
而题目中要求的区间:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
#define max_ 8010
#define inf 0x3f3f3f3f
#define lson i<<1,l,mid
#define rson i<<1|1,mid+1,r
#define ll long long
using namespace std;
struct node
{
int l,r,w;//w储存当前区间的颜色 初始化为-1
};
struct node tree[max_*4];
int n,last;
int col[max_];//记录各种颜色的个数
void built(int i,int l,int r)
{
tree[i].l=l;
tree[i].r=r;
tree[i].w=-1;
if(l==r)
return;
int mid=(l+r)>>1;
built(lson);
built(rson);
}
void updata(int i,int l,int r,int v)
{
if(tree[i].l==l&&tree[i].r==r)
{
tree[i].w=v;
return;
}
if(tree[i].w!=-1)
{
tree[i<<1].w=tree[i<<1|1].w=tree[i].w;
tree[i].w=-1;
}
int mid=(tree[i].l+tree[i].r)>>1;
if(r<=mid)
updata(i<<1,l,r,v);
else if(l>mid)
updata(i<<1|1,l,r,v);
else
{
updata(i<<1,l,mid,v);
updata(i<<1|1,mid+1,r,v);
}
}
void query(int i)
{
if(tree[i].w!=-1)
{
if(tree[i].w!=last)
{
col[tree[i].w]++;
last=tree[i].w;
}
return;
}
if(tree[i].l==tree[i].r)
return;
query(i<<1);
query(i<<1|1);
}
int main(int argc, char const *argv[])
{
while(scanf("%d",&n)!=EOF)
{
memset(col,0,sizeof(col));
memset(tree,-1,sizeof(tree));
int i;
built(1,1,8000);
for(i=1;i<=n;i++)
{
int x,y,t;
scanf("%d%d%d",&x,&y,&t);
if(x<y)
updata(1,x+1,y,t);
}
last=-1;
query(1);
for(i=0;i<max_;i++)
{
if(col[i]>0)
printf("%d %d\n",i,col[i]);
}
printf("\n");
}
return 0;
}