题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1698
这道题是成段更新,使用延迟标记,对于当前的left<=l&&right>=r直接返回,等到下次更新搜索到时候才向下更新,push_down;
#include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #define MAXN 200010 int color[MAXN<<2]; int tree[MAXN<<2]; void build_tree(int l,int r,int id); void up_date_tree(int left,int right,int l,int r,int id,int value); void push_down(int l,int r,int id); void push_up_tree(int id); int main() { int tcase,i,j,k,n,value,left,right,num; while(scanf("%d",&tcase)==1) { for(j=1;j<=tcase;j++) { scanf("%d",&n); build_tree(1,n,1); scanf("%d",&num); for(i=0;i<num;i++) { scanf("%d%d%d",&left,&right,&value); up_date_tree(left,right,1,n,1,value); } printf("Case %d: The total value of the hook is %d.\n",j,tree[1]); } } } void build_tree(int l,int r,int id) { color[id]=0; if(l==r) { tree[id]=1; return ; } tree[id]=r-l+1; int mid=l+r>>1; build_tree(l,mid,id<<1); build_tree(mid+1,r,id<<1|1); } void up_date_tree(int left,int right,int l,int r,int id,int value) { if(left<=l&&right>=r) { tree[id]=(r-l+1)*value; color[id]=value; return ; } push_down(l,r,id); int mid=l+r>>1; if(left<=mid) up_date_tree(left,right,l,mid,id<<1,value); if(right>mid) up_date_tree(left,right,mid+1,r,id<<1|1,value); push_up_tree(id); } void push_down(int l,int r,int id) { if(color[id]) { color[id<<1]=color[id]; color[id<<1|1]=color[id]; int mid=l+r>>1; tree[id<<1]=(mid-l+1)*color[id]; tree[id<<1|1]=(r-mid)*color[id]; } color[id]=0; } void push_up_tree(int id) { tree[id]=tree[id<<1]+tree[id<<1|1]; }