nbut线段树专题F - A Simple Problem with Integers

来源:互联网 发布:完美告白知乎 编辑:程序博客网 时间:2024/05/29 18:02

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 abc" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q ab" means querying the sum of AaAa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

不要用int,用__int64 或者 long long


#include<stdio.h>
#define maxn 100010

struct node
{
__int64 val;
int l,r;
__int64 add;
}tree[maxn*4];
__int64 num[maxn];

void pushdown(int p)
{
int m=(tree[p].r-tree[p].l+1);
if(tree[p].add)
{
tree[p<<1].add+=tree[p].add;
tree[p<<1|1].add+=tree[p].add;
tree[p<<1].val+=tree[p].add*(m-(m>>1));
tree[p<<1|1].val+=tree[p].add*(m>>1);
tree[p].add=0;
}
}

void build(int p,int l,int r)
{
tree[p].l=l;
tree[p].r=r;
tree[p].add=0;
if(l==r)
{
tree[p].val=num[l-1];
return ;
}
int mid=(l+r)>>1;
build(p<<1,l,mid);
build(p<<1|1,mid+1,r);
tree[p].val=tree[p<<1].val+tree[p<<1|1].val;
}

void update(int p,int l,int r,__int64 val)
{
if(l<=tree[p].l && r>=tree[p].r)
{
tree[p].val+=(__int64 )(tree[p].r-tree[p].l+1)*val;
tree[p].add+=val;
return ;
}
pushdown(p);
int mid=(tree[p].r+tree[p].l)>>1;
if(r<=mid)
update(p<<1,l,r,val);
else if(l>mid)
update(p<<1|1,l,r,val);
else
{
update(p<<1,l,mid,val);
update(p<<1|1,mid+1,r,val);
}
tree[p].val=tree[p<<1].val+tree[p<<1|1].val;
}

__int64 sum;
void query(int p,int l,int r)
{
if(l<=tree[p].l && r>=tree[p].r)
{
sum+=tree[p].val;
return ;
}
pushdown(p);
int mid=(tree[p].r+tree[p].l)>>1;
if(r<=mid)
query(p<<1,l,r);
else if(l>mid)
query(p<<1|1,l,r);
else
{
query(p<<1,l,mid);
query(p<<1|1,mid+1,r);
}
}

int main()
{
int n,q;
while(~scanf("%d%d",&n,&q))
{
for(int i=0;i<n;i++)
scanf("%I64d",&num[i]);
build(1,1,n);
char op[3];
int x,y;
long long val;
while(q--)
{
scanf("%s",op);
if(op[0]=='Q')
{
scanf("%d%d",&x,&y);
sum=0;
query(1,x,y);
printf("%I64d\n",sum);
}
else if(op[0]=='C')
{
scanf("%d%d%I64d",&x,&y,&val);
update(1,x,y,val);
}
}
}
return 0;
}


0 0
原创粉丝点击