您的位置:首页 > 其它

线段树之ZOJ1610 Count the Colors

2015-08-10 13:36 357 查看
成段替换的模型。

这一题告诉你的是要涂色的点的范围,而线段树内节点表示的是区间的颜色(原谅我拙计的语文)。可以和POJ2528 对比,就能发现区别了。

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <sstream>
using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

typedef long long LL;
const double pi=4.0*atan(1.0);
const int MAXN=10005;
int num[MAXN],ans[MAXN];
int add[MAXN<<2];//lazy标志,-1表示未涂色
int col[MAXN];
int temp;
void PushDown(int rt)
{//如果该段有颜色,那么就更新到孩子,自身变回-1
if(add[rt]!=-1)
{
add[rt<<1]=add[rt];
add[rt<<1|1]=add[rt];
add[rt]=-1;
}
}

void build(int l,int r,int rt)//全部清为-1,所以可以直接用memset
{
add[rt]=-1;
if(l==r)
{
return ;
}
int m=(l+r)>>1;
build(lson);
build(rson);

}
//这里很简单,就是修改某段的颜色
void update(int L,int R,int c,int l,int r,int rt)
{
if(L<=l && r<=R)
{
add[rt]=c;
return ;
}

PushDown(rt);
int m=(l+r)>>1;

if(L<=m)
update(L,R,c,lson);
if(m<R)
update(L,R,c,rson);

}
//查询,相当于要查全部的叶子节点,但是可以优化,某段有颜色,那么记录,该段以下不用查询,可以直接返回,因为它下面也一定是这个颜色
void query(int l,int r,int rt)
{
if(add[rt]!=-1)
{
for(int i=l;i<=r;i++)
col[i]=add[rt];
return ;
}
if(l==r)//如果查到叶子节点了,就必须返回,否则会跪
return ;
int m=(l+r)>>1;//如果是-1,还要查询下去,因为有可能它的孩子节点有颜色
query(lson);
query(rson);
}

int main()
{
int n,m;
int i,j,k;
int x,y,z;
int T;
int Max;
while(scanf("%d",&n)!=EOF)
{

memset(add,-1,sizeof(add));
Max=0;
for(i=0;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
Max=max(Max,z);
if(x==y)
continue;
else
{
update(x+1,y,z,1,8005,1);
}

}
memset(col,-1,sizeof(col));
memset(ans,0,sizeof(ans));
memset(num,0,sizeof(num));

query(1,8005,1);
int pre=-1;
for(i=1;i<MAXN;i++)
{
if(col[i]!=pre)
{
pre=col[i];
if(pre==-1)
continue;
ans[col[i]]=1;

num[col[i]]++;
}
}
//printf("%d\n",i);
for(i=0;i<=Max;i++)
if(ans[i])
printf("%d %d\n",i,num[i]);
printf("\n");
}

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