HDU 1698
一道线段树的区间修改题,和POJ3468非常类似,都是利用lazy-tag来加快速度,lazy-tag在poj 3468的解题报告中有说明。不同之处在于这里是更改stick的类型,所以对tag直接赋值就行了。另外,初始的stick为1,所以在建树的时候需要注意。
#include<stdio.h> #include<string.h> #define MAX_HOOK 100005 struct node { int left; int right; int sum; int tag; }stick[4*MAX_HOOK]; void build(int,int,int); void update(int,int,int,int); void pushdown(int); void pushup(int); int query(int,int,int); int main() { int t,cas=1; scanf("%d",&t); while(t--) { int n,q,i; scanf("%d",&n); memset(stick,0,sizeof(stick)); build(1,1,n); scanf("%d",&q); for(i=0;i<q;i++) { int x,y,z; scanf("%d%d%d",&x,&y,&z); update(1,x,y,z); } printf("Case %d: The total value of the hook is %d.\n",cas++,query(1,1,n)); } return 0; } void build(int root,int le,int ri) { stick[root].left=le; stick[root].right=ri; stick[root].sum=1; if(le==ri) return ; int mid=(le+ri)/2; build(2*root,le,mid); build(2*root+1,mid+1,ri); pushup(root); } void update(int root,int le,int ri,int val) { if(le<=stick[root].left&&ri>=stick[root].right) { stick[root].sum=(stick[root].right-stick[root].left+1)*val; stick[root].tag=val; return ; } if(le>stick[root].right||ri<stick[root].left) { return ; } pushdown(root); update(2*root,le,ri,val); update(2*root+1,le,ri,val); pushup(root); } void pushup(int root) { stick[root].sum=stick[root*2].sum+stick[root*2+1].sum; } void pushdown(int root) { if(stick[root].tag) { stick[2*root].sum=(stick[2*root].right-stick[2*root].left+1)*stick[root].tag; stick[2*root+1].sum=(stick[2*root+1].right-stick[2*root+1].left+1)*stick[root].tag; stick[2*root].tag=stick[root].tag; stick[2*root+1].tag=stick[root].tag; stick[root].tag=0; } } int query(int root,int le,int ri) { if(le<=stick[root].left&&ri>=stick[root].right) { return stick[root].sum; } if(le>stick[root].right||ri<stick[root].left) { return 0; } return query(2*root,le,ri)+query(2*root+1,le,ri); }