现在的位置: 首页 > 综合 > 正文

HDU_1556 Color the ball(线段树)

2012年07月16日 ⁄ 综合 ⁄ 共 1202字 ⁄ 字号 评论关闭

  结构体中定义记录染色次数的参数(cov),更新时直接找到对应的区间,使cov++。查询时要有点小操作。

查询过程:

void query(当前节点 t,要查询的点 x)
{
  
  if(找到要查询的点)
  
return cov;
  
  if(该点的cov > 0
{
 左孩子.cov
+= 当前节点.cov;
        右孩子.cov
+= 当前节点.cov;
 当前节点.cov
= 0;
    }
mid
= (左孩子+右孩子) >> 1;
if(x <= mid)
             query(左孩子, x);
else
  query(右孩子, x);
}

下边是完整的代码:

View Code

#include <stdio.h>
#define N 100010
struct node
{
int l, r;
int cov;
}node[N
*4];
int ans;
void creat(int t, int l, int r)
{
node[t].l
= l;
node[t].r
= r;
node[t].cov
= 0;
if(l == r) return;
int mid = (node[t].l + node[t].r) >> 1;
creat(t
<<1, l, mid);
creat(t
<<1|1, mid+1, r);
}
void updata(int t, int l, int r)
{
if(node[t].l >= l && node[t].r <= r)
{
node[t].cov
++;
return;
}
int mid = (node[t].l + node[t].r) >> 1;
if(l > mid)
updata(t
<<1|1, l, r);
else if(r <= mid)
updata(t
<<1, l, r);
else
{
updata(t
<<1, l, mid);
updata(t
<<1|1, mid+1, r);
}
}
void query(int t, int x)
{
if(node[t].l == node[t].r)
{
ans
= node[t].cov;
return;
}
if(node[t].cov > 0)
{
node[t
<<1].cov += node[t].cov;
node[t
<<1|1].cov += node[t].cov;
node[t].cov
= 0;
}
int mid = (node[t].l + node[t].r) >> 1;
if(x <= mid) query(t<<1, x);
else query(t<<1|1, x);
}
int main()
{
int n, i, x, y;
//freopen("data.in", "r", stdin);
while(scanf("%d", &n), n)
{
creat(
1, 1, n);
for(i = 1; i <= n; i++)
{
scanf(
"%d%d", &x, &y);
updata(
1, x, y);
}
for(i = 1; i < n; i++)
{
query(
1, i);
printf(
"%d ", ans);//printf("ok\n");
}
query(
1, n);
printf(
"%d\n", ans);
}
return 0;
}

抱歉!评论已关闭.