您的位置:首页 > 其它

A Simple Problem with Integers ----线段树的模板题

2017-08-11 14:38 253 查看
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 abc" means adding c to each of Aa,
Aa+1, ... ,
Ab. -10000 ≤ c ≤ 10000.

"Q ab" 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.
#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll __int64
using namespace std;
const  int Maxn=100000+100;

ll  a[Maxn];
struct node{
ll l;
ll r;
ll value;
ll add;
ll  mid;
};
node tree[3*Maxn];
void build(ll v,ll l,ll r)
{
tree[v].l=l;
tree[v].r=r;
tree[v].add=0;
tree[v].mid=(l+r)/2;
if(l==r){
tree[v].value=a[l];
return ;
}
build(2*v,l,tree[v].mid);
build(2*v+1,tree[v].mid+1,r);
tree[v].value=tree[2*v].value+tree[2*v+1].value;
}

void down_add(ll v){
ll lc=2*v,rc=2*v+1;
tree[lc].add+=tree[v].add;
tree[rc].add+=tree[v].add;
tree[v].value+=tree[v].add*(tree[v].r-tree[v].l+1);
tree[v].add=0;
}

void update(ll v,ll l,ll r,ll m){
if (tree[v].l==l&&tree[v].r==r){
tree[v].add+=m;
return;
}
tree[v].value+=m*(r-l+1);
if(tree[v].add){
down_add(v);
}
if(r<=tree[v].mid)
update(v*2,l,r,m);
else if(l>tree[v].mid)
update(v*2+1,l,r,m);
else{
update(v*2,l,tree[v].mid,m);
update(v*2+1,tree[v].mid+1,r,m);
}
}
ll  query(ll v,ll l,ll r){
if(tree[v].l==l&&tree[v].r==r){
return tree[v].value+tree[v].add*(r-l+1);
}
if(tree[v].add){
down_add(v);
}
if(r<=tree[v].mid){
return query(2*v,l,r);
}
else if(l>tree[v].mid){
return query(v*2+1,l,r);
}
else{
return query(2*v,l,tree[v].mid)+query(2*v+1,tree[v].mid+1,r);
}
}
int main()
{
ll N,Q,l,r,m;
scanf("%I64d%I64d",&N,&Q);
for(int i=1;i<=N;i++)
scanf("%I64d",&a[i]);
build(1,0,N);
for(int i=0;i<Q;i++)
{
char c[10];
scanf("%s",c);
if(c[0]=='Q'){
scanf("%I64d%I64d",&l,&r);
printf("%I64d\n",query(1,l,r));
}
else
{
scanf("%I64d%I64d%I64d",&l,&r,&m);
update(1,l,r,m);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: