HDU 1698 线段树 区间更新求和

时间:2022-01-07 21:20:36

一开始这条链子全都是1

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
using namespace std;
///线段树 区间更新
#define MAX 100050
struct node
{
int left;
int right;
int mark;
int total;
};
node tree[MAX*4];
int build(int root,int left,int right)
{
tree[root].left=left;
tree[root].right=right;
tree[root].mark=1;
if(left==right)
{
return tree[root].total=0;
}
int mid=(left+right)>>1;
tree[root].total=(build(root<<1,left,mid)+build(root<<1|1,mid+1,right)); }
void update_mark(int root)
{
if(tree[root].mark!=0)
{
tree[root].total=(tree[root].right-tree[root].left+1)*tree[root].mark;
if(tree[root].left!=tree[root].right)
{
tree[root<<1].mark=tree[root<<1|1].mark=tree[root].mark;
}
tree[root].mark=0;
}
}
int update(int root,int l,int r,int va)
{
update_mark(root);
if(r<tree[root].left||l>tree[root].right)
return tree[root].total;
if(l<=tree[root].left&&r>=tree[root].right)
{
tree[root].mark=va;
return tree[root].total=(tree[root].right-tree[root].left+1)*va;
}
return tree[root].total=(update(root<<1,l,r,va)+update(root<<1|1,l,r,va));
}
int cal(int root,int l,int r)
{
update_mark(root);
if(r<tree[root].left||l>tree[root].right)
return 0;
if(l<=tree[root].left&&r>=tree[root].right)
{
return tree[root].total;
}
return (root<<1,l,r)+cal(root<<1|1,l,r);
}
int main(){
int t;
scanf("%d",&t);
int tt=0;
while(t--)
{
tt++;
int n;
scanf("%d",&n);
build(1,1,n);
int q;
scanf("%d",&q);
for(int i=0;i<q;i++)
{
int l,r;
int val;
scanf("%d%d%d",&l,&r,&val);
update(1,l,r,val);
}printf("Case %d: The total value of the hook is %d.\n",tt,cal(1,1,n ));
}
}