hdu698 Just a Hook 线段树-成段更新

时间:2023-03-08 18:50:17
hdu698 Just a Hook 线段树-成段更新

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698

很简单的一个线段树的题目,每次更新采用lazy思想,这里我采用了增加一个变量z,z不等于0时其绝对值表示当前区间的牌的性质并且代表更新到此区间

代码:

 #include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
using namespace std;
#define maxn 100010
class node
{
public:
int l;
int r;
int sum;
int z;
};
int n;
int q;
int x,y,z;
node segTree[maxn*];
void build(int num, int l,int r)
{
segTree[num].l=l;
segTree[num].r=r;
segTree[num].z=;
if(l==r)
{
segTree[num].sum=;
return ;
}
int mid=(l+r)/;
build(num*,l,mid);
build(num*+,mid+,r);
segTree[num].sum=segTree[num*].sum+segTree[num*+].sum;
}
void Update(int num,int l,int r,int z)
{
if(segTree[num].l ==l && segTree[num].r ==r)
{
segTree[num].z=z;
segTree[num].sum=(segTree[num].r- segTree[num].l +)*segTree[num].z;
return ;
}
int mid=(segTree[num].l + segTree[num].r)/;
if(segTree[num].z)
{
Update(num*,segTree[num].l,mid,segTree[num].z);
Update(num*+,mid+,segTree[num].r,segTree[num].z);
segTree[num].z=;
} if(r<=mid)
Update(num*,l,r,z);
else if(l>mid) Update(num*+,l,r,z);
else
{
Update(num*,l,mid,z);
Update(num*+,mid+,r,z);
}
segTree[num].sum = segTree[num*].sum + segTree[num*+].sum;
}
int main()
{
int t;
scanf("%d",&t);
int iCase=;
while(t--)
{
scanf("%d%d",&n,&q);
build(,,n);
for(int i=;i<q;i++)
{
scanf("%d%d%d",&x,&y,&z);
Update(,x,y,z);
}
cout<<"Case "<<iCase++<<":"<<" The total value of the hook is "<<segTree[].sum<<"."<<endl; }
return ;
}