您的位置:首页 > 其它

hdu 1698 Just a Hook 线段树区间更新

2015-04-03 22:15 453 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698

Let us number the consecutive metallic sticks of the hook from 1 to N. For each operation, Pudge can change the consecutive metallic sticks, numbered from X to Y, into cupreous sticks, silver sticks or golden sticks.
The total value of
the hook is calculated as the sum of values of N metallic sticks. More
precisely, the value for each kind of stick is calculated as follows:

For
each cupreous stick, the value is 1.
For each silver stick, the value is
2.
For each golden stick, the value is 3.

Pudge wants to know the
total value of the hook after performing the operations.
You may consider the
original hook is made up of cupreous sticks.

题意描述:给出n个数,初始化为1,然后Q个操作,每个操作x,y,z如下:

z为1:更新从第x个数到第y个数连续区间为1.

z为2:更新从第x个数到第y个数连续区间为2.

z为3:更新从第x个数到第y个数连续区间为3.

最后求出这个n个数的和。

算法分析:线段树区间更改的做法,设立sum[]和col[](lazy标记)。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define inf 0x7fffffff
using namespace std;
const int maxn=100000+10;

int n,q;
int sum[maxn<<2],col[maxn<<2];

void PushUP(int rt) {sum[rt]=sum[rt<<1]+sum[rt<<1|1]; }
void PushDown(int rt,int m)
{
if (col[rt]!=-1)
{
col[rt<<1]=col[rt<<1|1]=col[rt];
sum[rt<<1]=(m-m/2)*col[rt];
sum[rt<<1|1]=(m/2)*col[rt];
col[rt]=-1;
}
}

void build(int l,int r,int rt)
{
col[rt]=-1;
if (l==r)
{
sum[rt]=1;
return;
}
int m=(l+r)>>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
PushUP(rt);
}

void update(int l,int r,int rt,int x,int y,int z)
{
if (x<=l && r<=y)
{
col[rt]=z ;sum[rt]=(r-l+1)*z;
return;
}
int mid=(l+r)>>1;
PushDown(rt,r-l+1);
if (y<=mid) update(l,mid,rt<<1,x,y,z);
else if (x>mid) update(mid+1,r,rt<<1|1,x,y,z);
else {update(l,mid,rt<<1,x,mid,z);update(mid+1,r,rt<<1|1,mid+1,y,z); }
PushUP(rt);
}

void query(int l,int r,int rt)
{
if (l==r) return;
PushDown(rt,r-l+1);
int mid=(l+r)>>1;
query(l,mid,rt<<1);
query(mid+1,r,rt<<1|1);
PushUP(rt);
}

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