标签:long div const return 了解 turn algorithm query uil
之前一直没手写过线段树,今日手写线段树发现模板理解起来还是很容易的,lazy标记的用法也大概了解了一点,但对于线段树的理解应该还不是很好(等学会线段树的时候就学树链剖分,立个flag)
下面是poj3468代码
#include <cstdio> #include <algorithm> #include <iostream> using namespace std; const int maxn=100000+5; int num[maxn]; struct node { int l,r; long long sum,lazy; }tree[maxn*4]; void build(int i,int l,int r) { tree[i].l=l; tree[i].r=r; tree[i].lazy=0; if(l==r) { tree[i].sum=num[l]; return ; } int mid=(l+r)>>1; build(i<<1,l,mid); build(i<<1|1,mid+1,r); tree[i].sum=tree[i<<1].sum+tree[i<<1|1].sum; } void update(int i,int a,int b,long long val) { if(tree[i].l==a&&tree[i].r==b) { tree[i].lazy+=val; return ; } tree[i].sum+=val*(b-a+1); int mid=(tree[i].l+tree[i].r)>>1; if(b<=mid) update(i<<1,a,b,val); else if(a>mid) update(i<<1|1,a,b,val); else{ update(i<<1,a,mid,val); update(i<<1|1,mid+1,b,val); } } long long query(int i,int a,int b) { if(tree[i].l==a&&tree[i].r==b) { return tree[i].sum+(b-a+1)*tree[i].lazy; } tree[i].sum+=(tree[i].r-tree[i].l+1)*tree[i].lazy; int mid=(tree[i].l+tree[i].r)>>1; update(i<<1,tree[i].l,mid,tree[i].lazy); update(i<<1|1,mid+1,tree[i].r,tree[i].lazy); tree[i].lazy=0; if(b<=mid) return query(i<<1,a,b); else if(a>mid) return query(i<<1|1,a,b); else return query(i<<1,a,mid)+query(i<<1|1,mid+1,b); } int main() { int n,q; while(~scanf("%d%d",&n,&q)) { for(int i=1;i<=n;i++) scanf("%d",&num[i]); build(1,1,n); for(int i=0;i<q;i++){ char ch; cin>>ch; if(ch==‘C‘){ int a,b,c; scanf("%d%d%d",&a,&b,&c); update(1,a,b,c); } else{ int a,b; scanf("%d%d",&a,&b); // printf("test\n"); printf("%lld\n",query(1,a,b)); } } } return 0; } /* 10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4 */
标签:long div const return 了解 turn algorithm query uil
原文地址:http://www.cnblogs.com/lalalatianlalu/p/7956008.html