线段树的区间改变,基本板子。线段树学了一下午加一晚上,推荐一个大佬的博客,写的非常好:
#include#include #include #include using namespace std;const int maxn=100000+100;struct setree{ int val,am;}tree[maxn*3];int m,n;int a[maxn];void build(int root,int a[],int l,int r){ tree[root].am=0; if(l==r) { tree[root].val=a[l]; return; } int mid=(l+r)/2; build(root*2,a,l,mid); build(root*2+1,a,mid+1,r); tree[root].val=tree[root*2].val+tree[root*2+1].val;}void update(int root,int l,int r,int p,int q,int vval){ if(q r) return; if(l>=p&&r<=q) { tree[root].val=vval*(r-l+1); tree[root].am=vval; return; } int mid=(l+r)/2; int x=root; if(tree[x].am) { tree[2*x].am=tree[x].am;//改了改延迟标记,使它等于要变成的数 tree[2*x+1].am=tree[x].am; tree[2*x].val=tree[x].am*(mid-l+1);//区间的值等于区间长度乘以要变成的值 tree[2*x+1].val=tree[x].am*(r-mid); tree[x].am=0; } update(root*2,l,mid,p,q,vval); update(root*2+1,mid+1,r,p,q,vval); tree[root].val=tree[root*2].val+tree[root*2+1].val;}int t;int main(){ scanf("%d",&t); for(int zz=1;zz<=t;zz++) { scanf("%d",&n); for(int i=1;i<=n;i++) a[i]=1; build(1,a,1,n); scanf("%d",&m); for(int i=1;i<=m;i++) { int aa,bb,cc; scanf("%d%d%d",&aa,&bb,&cc); update(1,1,n,aa,bb,cc); } printf("Case %d: The total value of the hook is %d.\n",zz,tree[1].val); } return 0;}
http://www.cnblogs.com/TenosDoIt/p/3453089.html