数据量比较大,所以要用线段树处理!!在加以个数后,不要把父结点的所有子结点都加上,这要比较费时间,用一个nsum存储,在寻找区间段的和时,按需要往下加!!另外数据位数比较大,超过了32位,用int类型肯定不行,要用__int64!!具体看代码的注释!!
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
代码:
#include<iostream>
#include<stdio.h>
using namespace std;
struct node
{
int r,l;
__int64 sum,nsum;
node *le,*re;
}tree[1000000];
int count;
void build(node *root,int l,int r)
{
root->sum=0;
root->nsum=0;
root->l=l;
root->r=r;
if(l!=r)
{
count++;
root->le=tree+count;
count++;
root->re=tree+count;
build(root->le,l,(l+r)/2);
build(root->re,(l+r)/2+1,r);
}
}
void insert(node *root,int i,int a)
{
if(root->l==i && root->r==i)
{
root->sum=a;
return ;
}
root->sum+=a;
if(i<=(root->r+root->l)/2)
insert(root->le,i,a);
else
insert(root->re,i,a);
}
void add(node* root,int c,int d,long b)
{
if(c==root->l && d==root->r)
{
root->nsum+=b;
return ;
}
root->sum+=b*(d-c+1);
if(d<=(root->r+root->l)/2)
add(root->le,c,d,b);
else if(c>=(root->r+root->l)/2+1)
add(root->re,c,d,b);
else
{
add(root->le,c,(root->r+root->l)/2,b);
add(root->re,(root->r+root->l)/2+1,d,b);
}
}
__int64 qsum(node *root,int c,int d)
{
if(c==root->l && d==root->r)
return root->sum+root->nsum*(d-c+1);
root->sum+=(root->r-root->l+1)*root->nsum; //不是要求的区间的话就把要加的值往下加
add(root->le,root->l,(root->r+root->l)/2,root->nsum);
add(root->re,(root->r+root->l)/2+1,root->r,root->nsum);
root->nsum=0;
if(d<=(root->r+root->l)/2)
return qsum(root->le,c,d);
else if(c>=(root->r+root->l)/2+1)
return qsum(root->re,c,d);
else
{
return qsum(root->le,c,(root->r+root->l)/2)+qsum(root->re,(root->r+root->l)/2+1,d);
}
}
int main()
{
int m,n,i,c,d;
char e;
__int64 a,b,f;
scanf("%d%d",&m,&n);
count=0;
build(tree,1,m);
for(i=1;i<=m;i++)
{
scanf("%I64d",&a);
insert(tree,i,a);
}
for(i=0;i<n;i++)
{
scanf("%s",&e);
if(e=='Q')
{
scanf("%d%d",&c,&d);
f=qsum(tree,c,d);
printf("%I64d\n",f);
}
else
{
scanf("%d%d",&c,&d);
scanf("%I64d",&b);
add(tree,c,d,b);
}
}
return 0;
}