标签:des style blog http color os
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 55626 | Accepted: 16755 | |
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
线段树+延迟标记
#include"stdio.h" #include"string.h" #define N 100005 int num[N]; struct node { int l,r; __int64 s,a; }f[N*3]; void creat(int t,int l,int r) { f[t].l=l; f[t].r=r; f[t].a=0; if(l==r) { f[t].s=num[r]; return ; } int temp=t*2,mid=(l+r)/2; creat(temp,l,mid); creat(temp+1,mid+1,r); f[t].s=f[temp].s+f[temp+1].s; return ; } void update(int t,int l,int r,__int64 a) { if(f[t].l==l&&f[t].r==r) { f[t].a+=a; //每次都是s先增加,a记录下一层的增量 f[t].s+=(f[t].r-f[t].l+1)*a; return ; //不再向下一层更新 } int temp=t*2,mid=(f[t].l+f[t].r)/2; if(f[t].a) { f[temp].a+=f[t].a; f[temp].s+=(f[temp].r-f[temp].l+1)*f[t].a; f[temp+1].a+=f[t].a; f[temp+1].s+=(f[temp+1].r-f[temp+1].l+1)*f[t].a; f[t].a=0; //完成向下一层的加和,进行归零 } if(r<=mid) update(temp,l,r,a); else if(l>mid) update(temp+1,l,r,a); else { update(temp,l,mid,a); update(temp+1,mid+1,r,a); } f[t].s=f[temp].s+f[temp+1].s; return ; } __int64 find(int t,int l,int r) { if(f[t].l==l&&f[t].r==r) { return f[t].s; } int temp=t*2,mid=(f[t].l+f[t].r)/2; if(f[t].a) //下一层的更新还没完成 { f[temp].a+=f[t].a; f[temp].s+=(f[temp].r-f[temp].l+1)*f[t].a; f[temp+1].a+=f[t].a; f[temp+1].s+=(f[temp+1].r-f[temp+1].l+1)*f[t].a; f[t].a=0; } if(r<=mid) return find(temp,l,r); else if(l>mid) return find(temp+1,l,r); else return find(temp,l,mid)+find(temp+1,mid+1,r); } int main() { int i,n,q; int a,b,c; char ch; while(scanf("%d%d",&n,&q)!=-1) { for(i=1;i<=n;i++) scanf("%d",&num[i]); creat(1,1,n); while(q--) { getchar(); scanf("%c",&ch); if(ch==‘C‘) { scanf("%d%d%d",&a,&b,&c); update(1,a,b,c); } else { scanf("%d%d",&a,&b); printf("%I64d\n",find(1,a,b)); } } } return 0; }
poj 3468 A Simple Problem with Integers,码迷,mamicode.com
poj 3468 A Simple Problem with Integers
标签:des style blog http color os
原文地址:http://blog.csdn.net/u011721440/article/details/24620215