HDU1698 区间成段替换

HDU1698 Just a Hook
由于只需查询总和,所以输出tree[1].sum即可

#include<cstdio>
struct node{
    int left,right;
    int sum,add;
}tree[100001*4];
int c;
void Build(int l,int r,int cur){
    tree[cur].left=l;
    tree[cur].right=r;
    tree[cur].add=0;
    if(l==r){
        tree[cur].sum=1;
        return;
    }
    int mid=(l+r)/2;
    Build(l,mid,cur*2);
    Build(mid+1,r,cur*2+1);
    tree[cur].sum=tree[cur*2].sum+tree[cur*2+1].sum;
}
void Add(int cur,int m){
    if(tree[cur].add){
        tree[cur*2].add=tree[cur].add;//替换
        tree[cur*2+1].add=tree[cur].add;//替换
        tree[cur*2].sum=tree[cur].add*(m-m/2);//替换 tree[cur*2+1].sum=tree[cur].add*(m/2);//替换
        tree[cur].add=0;
    }
}
void Update(int l,int r,int cur){
    if(l==tree[cur].left&&r==tree[cur].right){
        tree[cur].add=c;//替换
        tree[cur].sum=c*(r-l+1);//替换
        return ;
    }
    Add(cur,tree[cur].right-tree[cur].left+1);
    int mid=(tree[cur].left+tree[cur].right)/2;
    if(r<=mid)Update(l,r,cur*2);
    else if(l>mid)Update(l,r,cur*2+1);
    else {
        Update(l,mid,cur*2);
        Update(mid+1,r,cur*2+1);
    }
    tree[cur].sum=tree[cur*2].sum+tree[cur*2+1].sum;
}
int main(){
    int T,n,q,l,r;
    scanf("%d",&T);
    for(int t=1;t<=T;t++){
        scanf("%d%d",&n,&q);
        Build(1,n,1);
        while(q--){
            scanf("%d%d%d",&l,&r,&c);
            Update(l,r,1);
        }
        printf("Case %d: The total value of the hook is %d.\n",t,tree[1].sum);
    }
    return 0;
}

你可能感兴趣的:(HDU1698 区间成段替换)