标签:poj
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 74705 | Accepted: 22988 | |
Case Time Limit: 2000MS |
Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1,
A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa,
Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... ,
Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
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
Sample Output
4 55 9 15
Hint
Source
#include<stdio.h> #include<string.h> #define M 100005 struct tree{ int l,r; __int64 sum,add; }tree[M<<2]; void pushup(int root) { if(tree[root].l==tree[root].r)return; tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum; return; } void pushdown(int root) { if(tree[root].l==tree[root].r)return; if(tree[root].add==0)return; tree[root<<1].add+=tree[root].add; tree[root<<1|1].add+=tree[root].add; tree[root<<1].sum=tree[root<<1].sum+(tree[root<<1].r-tree[root<<1].l+1)*tree[root].add; tree[root<<1|1].sum=tree[root<<1|1].sum+(tree[root<<1|1].r-tree[root<<1|1].l+1)*tree[root].add; tree[root].add=0; return; } void build(int l,int r,int root) { tree[root].l=l; tree[root].r=r; tree[root].sum=0; tree[root].add=0; if(l==r){ tree[root].sum=0; return; } int mid=l+r>>1; build(l,mid,root<<1); build(mid+1,r,root<<1|1); pushup(root); } void update(int l,int r,int root,__int64 z) { if(tree[root].l==l&&tree[root].r==r) { tree[root].sum=tree[root].sum+(r-l+1)*z; tree[root].add=tree[root].add+z; //有可能出现多次的更新操作,所以要将所有的add都累加起来。 return; } pushdown(root); int mid=tree[root].l+tree[root].r>>1; if(r<=mid)update(l,r,root<<1,z); else if(l>mid)update(l,r,root<<1|1,z); else { update(l,mid,root<<1,z); update(mid+1,r,root<<1|1,z); } pushup(root); return; } __int64 Query(int l,int r,int root) { if(l==tree[root].l&&r==tree[root].r){ return tree[root].sum; } pushdown(root); int mid=tree[root].l+tree[root].r>>1; if(r<=mid)return Query(l,r,root<<1); else if(l>mid)return Query(l,r,root<<1|1); else { return Query(l,mid,root<<1)+Query(mid+1,r,root<<1|1); } } int main() { int N,Q,i,j,k,a,b; __int64 c,d; char s[20]; while(scanf("%d%d",&N,&Q)!=EOF) { build(1,N,1); for(i=1;i<=N;i++) { scanf("%I64d",&d); update(i,i,1,d); } while(Q--) { scanf("%s%d%d",s,&a,&b); if(s[0]=='Q'){ printf("%I64d\n",Query(a,b,1)); } if(s[0]=='C'){ scanf("%I64d",&c); update(a,b,1,c); } } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
poj 3468 A Simple Problem with Integers(线段树、延迟更新)
标签:poj
原文地址:http://blog.csdn.net/aaaaacmer/article/details/47066135