首页 > 代码库 > poj 3468 A Simple Problem with Integers
poj 3468 A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 110087 | Accepted: 34277 | |
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 51 2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4
Sample Output
455915
Hint
Source
#include<cstdio>#define LL long longconst int N=100005;char a[10];LL p,q,d; LL sum[N*3],lazy[N*3];LL read(){ LL x=0,f=1; char c=getchar(); while(c<‘0‘||c>‘9‘){if(c==‘-‘)f=-1;c=getchar();} while(c<=‘9‘&&c>=‘0‘){x=x*10+c-‘0‘;c=getchar();}return x*f;}void update(int rt){ sum[rt]=sum[rt<<1]+sum[rt<<1|1];}void build(int l,int r,int rt){ if(l==r){ sum[rt]=read(); return ; } int mid=(l+r)>>1; build(l,mid,rt<<1); build(mid+1,r,rt<<1|1); update(rt);}void push_down(int rt,int len){ lazy[rt<<1]+=lazy[rt]; lazy[rt<<1|1]+=lazy[rt]; sum[rt<<1]+=(len-(len>>1))*lazy[rt]; sum[rt<<1|1]+=(len>>1)*lazy[rt]; lazy[rt]=0;}void modify(int l,int r,int rt){ if(p<=l&&q>=r) { lazy[rt]+=d; sum[rt]+=(LL)d*(r-l+1); return; } push_down(rt,r-l+1); int mid=(l+r)>>1; if(mid>=p) modify(l,mid,rt<<1); if(q>mid) modify(mid+1,r,rt<<1|1); update(rt);}LL query(int l,int r,int rt,int nowl,int nowr){ if(nowl<=l&&nowr>=r) { return sum[rt]; } if(lazy[rt])push_down(rt,r-l+1); int m=(r+l)>>1; LL ans=0; if(nowl<=m) ans+=query(l,m,rt<<1,nowl,nowr); if(nowr>m) ans+=query(m+1,r,rt<<1|1,nowl,nowr); return ans;}int n,m;int main(){ n=read();m=read(); build(1,n,1); while(m--) { scanf("%s",a);p=read(),q=read(); if(a[0]==‘Q‘) { printf("%lld\n",query(1,n,1,p,q)); } if(a[0]==‘C‘) { d=read(); modify(1,n,1); } } return 0;}
poj 3468 A Simple Problem with Integers