Count the Colors
Time Limit: 2 Seconds Memory Limit: 65536 KB
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
思路:
之前做过一次,这次又有另一个想法,就试了一下,果真对啦,很开心。。
区间更新,单点查询,开两个数组,一个记录颜色,另一个记录该颜色下的个数,比较裸的线段树。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100000+100;
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
struct node
{
int l,r,val,lazy;
}tree[maxn*4];
int color[maxn],ans[maxn];
void pushdown(int rt)
{
if(tree[rt].lazy)
{
tree[rt<<1].val=tree[rt].val;
tree[rt<<1|1].val=tree[rt].val;
tree[rt<<1].lazy=1;
tree[rt<<1|1].lazy=1;
tree[rt].lazy=0;
}
}
void build(int rt,int l, int r)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].val=-1;
tree[rt].lazy=0;
if(l==r)
{
return;
}
int mid=(l+r)/2;
build(lson);
build(rson);
}
void update(int rt,int l,int r,int w)
{
if(tree[rt].l==l&&tree[rt].r==r)
{
tree[rt].val=w;
tree[rt].lazy=1;
return;
}
pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/2;
if(l>mid)
{
update(rt<<1|1,l,r,w);
}
else if(mid>=r)
{
update(rt<<1,l,r,w);
}
else
{
update(lson,w);
update(rson,w);
}
return;
}
void query(int rt,int l,int r)
{
if(tree[rt].l==l&&tree[rt].r==r)
{
color[l]=tree[rt].val;
//printf("%d %d\n",l,color[l]);
return;
}
pushdown(rt);
int mid=(tree[rt].l+tree[rt].r)/2;
if(l>mid)
{
query(rt<<1|1,l,r);
}
else
{
query(rt<<1,l,r);
}
}
int main ()
{
int n;
while(~scanf("%d",&n))
{
memset(color,-1,sizeof(color));
memset(ans,0,sizeof(ans));
build(1,1,8800);
int i;
for(i=1;i<=n;i++)
{
int xx,yy,zz;
scanf("%d%d%d",&xx,&yy,&zz);
update(1,xx+1,yy,zz);
}
for(i=1;i<=8800;i++)
{
query(1,i,i);
// printf("%d ",color[i]);
if(color[i]!=-1&&color[i]!=color[i-1])
{
ans[color[i]]++;
}
}
for(i=0;i<=8800;i++)
{
if(ans[i]!=0)
{
printf("%d %d\n",i,ans[i]);
}
}
printf("\n");
}
}
本文介绍了一种利用线段树进行区间更新及单点查询的方法,以解决复杂颜色段统计问题。通过构建线段树并进行区间更新操作,实现对不同颜色区间的覆盖与计数。

被折叠的 条评论
为什么被折叠?



