數據量比較大,所以要用線段樹處理!!在加以個數後,不要把父結點的所有子結點都加上,這要比較費時間,用一個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;
}