POJ

来源:互联网 发布:晋中干部网络培训平台 编辑:程序博客网 时间:2024/06/03 21:14

POJ - 3468  A Simple Problem with Integers 

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
The sums may exceed the range of 32-bit integers.
题意:给你N个数,有两种操作,第一种操作是[L,R]的区间的值都加上一个数,第二种操作输出[L,R]区间的和,实现这两种操作

思路:典型的线段树区间改变问题,lazy延迟标记(这个对于我这个初学者来说真是很难理解),最近刚学线段树算法,这些使用简单的线段树算法的题总算能自己写出来了

代码写的长,但是很容易理解,一开始没有注意数据范围,wa了好几次
#include<stdio.h>#include<iostream>using namespace std;typedef long long LL; const int maxn=111111;struct NODE{int l,r;LL sum;LL lazy;}segTree[maxn<<2];void pushup(int num){segTree[num].sum=segTree[num<<1].sum+segTree[num<<1|1].sum;}void  build(int num,int l,int r){segTree[num].l=l;segTree[num].r=r;segTree[num].lazy=0;if(l==r){cin>>segTree[num].sum;return;}int mid=(l+r)>>1;build(num<<1,l,mid);build(num<<1|1,mid+1,r);pushup(num); }void pushdown(int num){segTree[num<<1].sum+=segTree[num].lazy*(segTree[num<<1].r-segTree[num<<1].l+1);segTree[num<<1|1].sum+=segTree[num].lazy*(segTree[num<<1|1].r-segTree[num<<1|1].l+1);segTree[num<<1].lazy+=segTree[num].lazy;segTree[num<<1|1].lazy+=segTree[num].lazy;segTree[num].lazy=0;}void update(int l,int r,int num,int c){if(segTree[num].l==l&&segTree[num].r==r){segTree[num].sum+=(LL)(r-l+1)*c;segTree[num].lazy+=c;return;}if(segTree[num].lazy) pushdown(num);int mid=(segTree[num].l+segTree[num].r)>>1;if(r<=mid) update(l,r,num<<1,c);else if(l>mid) update(l,r,num<<1|1,c);else{update(l,mid,num<<1,c);update(mid+1,r,num<<1|1,c);}pushup(num);}LL query(int l,int r,int num){LL ans=0;    if(segTree[num].l==l&&segTree[num].r==r)   return segTree[num].sum;if(segTree[num].lazy) pushdown(num);int mid=(segTree[num].l+segTree[num].r)>>1;if(r<=mid) ans+=query(l,r,num<<1);else if(l>mid) ans+=query(l,r,num<<1|1);else{ans+=query(l,mid,num<<1);ans+=query(mid+1,r,num<<1|1);}return ans;   }int main(void){int N,Q;scanf("%d%d",&N,&Q);build(1,1,N);while(Q--){char op[2];int a,b,c;scanf("%s",op);if(op[0]=='Q'){scanf("%d%d",&a,&b);printf("%lld\n",query(a,b,1));}else{scanf("%d%d%d",&a,&b,&c);update(a,b,1,c);}}return 0;}

原创粉丝点击