A Simple Problem with Integers POJ

来源:互联网 发布:淘宝电子兑换券 编辑:程序博客网 时间:2024/05/24 15:40
A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072KTotal Submissions: 117870 Accepted: 36662Case Time Limit: 2000MS

Description

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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

The sums may exceed the range of 32-bit integers.

Source

POJ Monthly--2007.11.25, Yang Yi

题目大意:在一个数组中询问一个区间和或者对于一个区间同时增加或者减少

#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <cmath>#include <cstdlib>#include <ctime>using namespace std;typedef long long LL;const int MAXN = 1e5 + 5;struct tree{LL flag,sum;}a[MAXN * 4 + 5];int n,m;void pushup(int deep){a[deep].sum = a[deep * 2].sum + a[deep * 2 + 1].sum;}void build(int l ,int r,int deep){a[deep].flag = 0;if(l == r){scanf("%lld",&a[deep].sum);return;}int mid = (l + r) / 2;build(l,mid,deep * 2);build(mid+1,r,deep * 2 + 1);pushup(deep);}void pushdown(int deep,int longs){if(a[deep].flag){a[deep * 2].flag += a[deep].flag;a[deep * 2 +1].flag += a[deep].flag;a[deep * 2].sum += a[deep].flag * (longs - longs / 2);a[deep * 2 + 1].sum += a[deep].flag * (longs / 2);a[deep].flag = 0;}}void update(int L , int R ,int k , int l , int  r, int deep){if( L <= l && r <= R){a[deep].flag += k;a[deep].sum += (LL) k * (r - l + 1);return;}pushdown(deep,r-l+1);int mid = (l + r) / 2;if(L <= mid) update(L,R,k,l,mid,deep * 2);if(mid < R) update(L,R,k,mid+1,r,deep * 2 + 1);pushup(deep);}LL query(int L,int R,int l,int r,int deep){if( L <= l && r <= R)return a[deep].sum;pushdown(deep,r-l+1);LL sum=0;int mid = (l + r) / 2;if(L <= mid) sum += query(L,R,l,mid,deep * 2);if(mid < R)  sum += query(L,R,mid+1,r,deep * 2 + 1);return sum;}int main(){char s[2];LL k;int x,y;scanf("%d%d",&n,&m);build(1 , n , 1);while(m--){scanf("%s",&s);if(s[0] == 'Q'){scanf("%d%d",&x,&y);printf("%lld\n",query(x , y , 1 , n , 1));  }else{scanf("%d%d%d",&x,&y,&k);update(x,y,k,1,n,1);}}return 0;}


原创粉丝点击