hdu 1698 线段树 just a “trick” *_*

View Code
//第一次做线段树,不怎么会,试着模仿别人的写法,修修改改
//继续努力!!!
//初始状态全为1,x,y,z代表把x->y区间改为z
#include<stdio.h>
#include
<string.h>
const int MAX=100010;
#define L(x) x<<1
#define R(x) x<<1|1
#define MID(x,y) (x+y)>>1
struct {int color,l,r;}node[3*MAX];
void treeinit()
{
memset(node,
0,sizeof(node));
}
void build(int p,int l,int r)
{
node[p].color
=1;
node[p].l
=l;node[p].r=r;
if(l==r-1) return ;
int mid=MID(l,r);
build(R(p),mid,r);
build(L(p),l,mid);
}
void update(int p,int l,int r,int color)
{
if(node[p].l==l && node[p].r==r)
{
node[p].color
=color;
return ;
}
if(node[p].color)//我认为最关键的地方:
//如果一个区间已经被某种颜色全部覆盖了,比如说(1,10);
//现在我们要修改(5,7)的颜色,那其他部分的颜色是不是应该保持不变?
//所以,我们要把父节点原有的信息传递给子节点,保存下来,即(1,4)、(6,10)是不用改变的
{
node[R(p)].color
=node[p].color;
node[L(p)].color
=node[p].color;
node[p].color
=0;
}
int mid=MID(node[p].l,node[p].r);
if(l>=mid)
update(R(p),l,r,color);
else
if(r<=mid)
update(L(p),l,r,color);
else
{
update(L(p),l,mid,color);
update(R(p),mid,r,color);
}
}
int query(int p)
{
if(node[p].color)
return node[p].color*(node[p].r-node[p].l);
return query(L(p))+query(R(p));
}
int main()
{
int cases=1,x,y,z,t,n,m;
scanf(
"%d",&t);
while(t--)
{
scanf(
"%d%d",&n,&m);
treeinit();
build(
1,0,n);
while(m--)
{
scanf(
"%d%d%d",&x,&y,&z);
update(
1,x-1,y,z);
}
printf(
"Case %d: The total value of the hook is %d.\n",cases++,query(1));
}
return 0;
}

  

posted @ 2011-08-30 13:26  Because Of You  Views(202)  Comments(0Edit  收藏  举报