您的位置:首页 > 其它

hdu 1698 线段树

2015-07-29 14:48 357 查看
因为最后要求的是区间和,所以其实color不用存下来,这里将color当做lazy标记:color为-1表示已经pushdown或为初始状态;color为1、2、3时表示区间为相应颜色。

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

const int N = 100001;

struct Node
{
int l, r, sum, color;
} node[N << 2];

void build( int i, int l, int r )
{
node[i].l = l, node[i].r = r, node[i].sum = r - l + 1, node[i].color = -1;
if ( l == r ) return ;
int mid = ( l + r ) >> 1;
build( i << 1, l, mid );
build( i << 1 | 1, mid + 1, r );
}

void pushup( int i )
{
node[i].sum = node[i << 1].sum + node[i << 1 | 1].sum;
}

void pushdown( int i )
{
if ( node[i].color != -1 )
{
int lc = i << 1, rc = lc | 1;
node[lc].color = node[rc].color = node[i].color;
node[lc].sum = ( node[lc].r - node[lc].l + 1 ) * node[i].color;
node[rc].sum = ( node[rc].r - node[rc].l + 1 ) * node[i].color;
node[i].color = -1;
}
}

void update( int i, int l, int r, int c )
{
if ( node[i].l == l && node[i].r == r )
{
node[i].color = c;
node[i].sum = ( r - l + 1 ) * c;
return ;
}
pushdown(i);
int mid = ( node[i].l + node[i].r ) >> 1;
if ( r <= mid )
{
update( i << 1, l, r, c );
}
else if ( l > mid )
{
update( i << 1 | 1, l, r, c );
}
else
{
update( i << 1, l, mid, c );
update( i << 1 | 1, mid + 1, r, c );
}
pushup(i);
}

int main ()
{
int t;
scanf("%d", &t);
for ( int _case = 1; _case <= t; _case++ )
{
int n, m;
scanf("%d%d", &n, &m);
build( 1, 1, n );
while ( m-- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
update( 1, a, b, c );
}
printf("Case %d: The total value of the hook is %d.\n", _case, node[1].sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: