Language:
A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 162897 Accepted: 50267
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
The sums may exceed the range of 32-bit integers.
題意:
開始有n個數,現在給你兩種操作,第一種 C a b c,將[a,b]區間裏面的值都加上c,操作2,Q a b
詢問區間[a,b]的和。
思路:這是一個區間更新區間查詢的裸題,網上大部分線段樹區間更新都是用結構體寫的,我是用數組寫的
代碼:
#pragma GCC optimize(2)
//#include<bits/stdc++.h>
#include<stdio.h>
#include<iostream>
#define ULL unsigned long long
#define LL long long
#define Max 1000005
#define mem(a,b) memset(a,b,sizeof(a));
#define pb push_back
#define mp make_pair
#define input ios::sync_with_stdio(false);cin.tie(0);
#define debug printf("debug!!!\n");
const LL mod=1e9+7;
const ULL base=131;
const LL LL_MAX=9223372036854775807;
using namespace std;
LL tree[Max*4],lazy[Max*4];
void build(int root,int l,int r){
if(l==r){
scanf("%lld",&tree[root]);
return ;
}
int mid=(l+r)/2;
build(2*root,l,mid);
build(2*root+1,mid+1,r);
tree[root]=tree[2*root]+tree[2*root+1];
}
inline void pushdown(int root,int l,int r){
if(lazy[root]!=0){
int mid=(l+r)/2;
tree[2*root]+=lazy[root]*(mid-l+1);
tree[2*root+1]+=lazy[root]*(r-mid);
lazy[2*root]+=lazy[root];
lazy[2*root+1]+=lazy[root];
lazy[root]=0;
}
}
void update(int root,int l,int r,int L,int R,int val){
if(l>=L && r<=R){
tree[root]+=val*(r-l+1);
lazy[root]+=val;
return ;
}
pushdown(root,l,r);
int mid=(l+r)/2;
if(L<=mid)
update(2*root,l,mid,L,R,val);
if(R>mid)
update(2*root+1,mid+1,r,L,R,val);
tree[root]=tree[2*root]+tree[2*root+1];
}
LL query(int root,int l,int r,int L,int R){
if(l>=L && r<=R)
return tree[root];
pushdown(root,l,r);
LL ans=0;
int mid=(l+r)/2;
if(L<=mid)
ans+=query(2*root,l,mid,L,R);
if(R>mid)
ans+=query(2*root+1,mid+1,r,L,R);
return ans;
}
int main()
{
int n,q;
scanf("%d%d",&n,&q);
build(1,1,n);
char s[5];
while(q--){
scanf("%s",s);
if(s[0]=='C'){
int a,b;
LL c;
scanf("%d%d%lld",&a,&b,&c);
update(1,1,n,a,b,c);
}else{
int a,b;
scanf("%d%d",&a,&b);
printf("%lld\n",query(1,1,n,a,b));
}
}
return 0;
}