A Simple Problem with Integers
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 262144/131072K (Java/Other)
Total Submission(s) : 40 Accepted Submission(s) : 13
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.
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.
You need to answer all Q commands in order. One answer in a line.
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
4 55 9 15
注意要用longlong。。。
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Node{
int l,r;
int lazy;
long long num,tag;
}tree[1000000];
long long A[100005];
void Build(int n,int l,int r){
//先将一棵树的各个元素初始化
tree[n].l = l;
tree[n].r = r;
tree[n].tag = 0;
tree[n].lazy = 0;
if(l == r){
tree[n].num = A[l];
return;
}
int mid = (l + r) / 2;
Build(2*n,l,mid);
Build(2*n+1,mid+1,r);
//分别建好一棵树的左右儿子之后,计算tree[n].num
tree[n].num = tree[2*n].num + tree[2*n+1].num;
}
//lazy标记的思想是修改到到确切的区间后,不再修改儿子
//只是用一个lazy标记,等以后修改或查找到这个区间
//再把lazy标记往下传
void Modify(int n,int x,int y,long long der){
//先得到所在区间的范围
int l = tree[n].l;
int r = tree[n].r;
int mid = (l + r) / 2;
//找到恰好的区间进行修改及lazy标记
if(l == x && r == y){
tree[n].lazy = 1;
tree[n].tag += der;
tree[n].num += der * (y - x + 1);
return;
}
//如果该区间有lazy标记,则修改儿子,并将标记清0
if(tree[n].lazy == 1){
tree[n].lazy = 0;
Modify(2*n,l,mid,tree[n].tag);
Modify(2*n+1,mid+1,r,tree[n].tag);
tree[n].tag = 0;
}
if(x <= mid)//修改左儿子的充要条件
Modify(2*n,x,min(y,mid),der);
if(y > mid)//修改右儿子的充要条件
Modify(2*n+1,max(mid+1,x),y,der);
tree[n].num = tree[2*n].num + tree[2*n+1].num;
}
long long Find(int n,int x,int y){
int l = tree[n].l;
int r = tree[n].r;
int mid = (l + r) / 2;
if(l == x && r == y){
return tree[n].num;
}
if(tree[n].lazy == 1){
tree[n].lazy = 0;
Modify(2*n,l,mid,tree[n].tag);
Modify(2*n+1,mid+1,r,tree[n].tag);
tree[n].tag = 0;
}
long long ans = 0;
if(x <= mid) ans += Find(2*n,x,min(mid,y));
if(y > mid) ans += Find(2*n+1,max(mid+1,x),y);
return ans;
}
int main(){
int n,q;
int i;
char op;
int a,b,c;
while(scanf("%d%d",&n,&q) != EOF){
for(i = 1;i <= n;i++){
scanf("%lld",&A[i]);
}
Build(1,1,n);
for(i = 0;i < q;i++){
getchar();
scanf("%c",&op);
if(op == 'Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",Find(1,a,b));
}
else{
scanf("%d%d%d",&a,&b,&c);
Modify(1,a,b,c);
}
}
}
return 0;
}