您的位置:首页 > 其它

zoj 1610 线段树,成段更新,查询有哪些段及其数量

2017-07-18 15:35 369 查看
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,1】表示一段,而不是 0  和  1 分别表示一段

主要问题就是计算有哪些颜色及其区间的颜色数量了

因为线段树在区间查询的时候,对于叶子节点来说,是从左边忘右开始进行遍历的

依照这个规律就可以对区间进行快速的遍历获取答案

之前错误的思想:每次跟新的时候向上更新一下,若两个叶子节点相同,那么父亲节点也相同,这样就可以合并两个区间了,但是不知道为什么错了

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define MAXN 8010
#define lson l,mid,p<<1
#define rson mid+1,r,p<<1|1
int sum[MAXN<<2],lazy[MAXN<<2];

void pushDown(int p)
{
if(lazy[p]!=-1)
{
lazy[p<<1]=lazy[p];
lazy[p<<1|1]=lazy[p];
lazy[p]=-1;
}
}
void update(int l,int r,int p,int L,int R,int num)
{
if(L<=l&&r<=R){
lazy[p]=num;
return;
}

pushDown(p);
int mid=(l+r)>>1;
if(mid>=L)
update(lson,L,R,num);
if(mid<R)
update(rson,L,R,num);
}

int last;
void query(int l,int r,int p)
{
if(l==r){
if(lazy[p]!=-1&&lazy[p]!=last)
sum[lazy[p]]++;
last=lazy[p];
return ;
}

pushDown(p);
int mid=(l+r)>>1;
query(rson);
query(lson);
}

int main()
{
int n;
freopen("in.txt","r",stdin);
while(scanf("%d",&n)!=EOF)
{
int a,b,c;
memset(sum,0,sizeof(sum));
memset(lazy,-1,sizeof(lazy));
for(int i=0;i<n;i++){
scanf("%d%d%d",&a,&b,&c);
if(a<b)
update(1,8000,1,a+1,b,c);
}
last=-1;
query(1,8000,1);

for(int i=0;i<=8000;i++){
if(sum[i])
printf("%d %d\n",i,sum[i]);
}
puts("");

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: