题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698
题意:给出一段1~n的区间,区间内所有数初始为1,现在可以修改区间内任意一段,问m次修改后区间的和
思路:区间更新以及区间询问,一个一个点进行修改复杂度太高,这里就使用了lazy标记,当整个区间都更改为val时,则用lazy标记该区间,并且更新sum,比较难理解的应该是只修改区间一部分时,要把当前的lazy标记推向当前节点的只节点,直到子节点代表的区间全需要修改为或者全不需要修改,更新sum,有一点不懂若我要查询某个区间而不是整个区间时要怎么办,应该和查询区间和是一样的方式?不过返回的是sum的值(还是比较喜欢树状数组)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #define maxn 100030 using namespace std; struct Tree { int l,r,date; }tree[maxn*3]; int sum[maxn*3],lazy[maxn*3]; void build(int root,int l,int r) { lazy[root]=0; sum[root]=r-l+1; tree[root].l=l; tree[root].r=r; if (l==r) { tree[root].date=1; return; } int mid=(l+r)>>1; build(root<<1,l,mid); build(root<<1|1,mid+1,r); tree[root].date=tree[root<<1].date+tree[root<<1|1].date; } void update(int root,int l,int r,int val) { if (tree[root].l>=l && tree[root].r<=r) { lazy[root]=val; sum[root]=(tree[root].r-tree[root].l+1)*val; return; } int mid=(tree[root].l+tree[root].r)>>1; if (lazy[root]!=0) { lazy[root<<1]=lazy[root]; lazy[root<<1|1]=lazy[root]; sum[root<<1]=lazy[root]*(mid-tree[root].l+1); sum[root<<1|1]=lazy[root]*(tree[root<<1|1].r-mid); lazy[root]=0; } if (l<=mid) update(root<<1,l,r,val); if (r>mid) update(root<<1|1,l,r,val); sum[root]=sum[root<<1]+sum[root<<1|1]; } int main() { int t,n,m,cas=0; scanf("%d",&t); while (t--) { memset(lazy,0,sizeof(lazy)); memset(sum,0,sizeof(sum)); scanf("%d%d",&n,&m); build (1,1,n); for (int i=0;i<m;i++) { int a,b,val; scanf("%d%d%d",&a,&b,&val); update(1,a,b,val); } printf("Case %d: The total value of the hook is %d.\n",++cas,sum[1]); } }