264. 數列操作
★☆ 輸入文件:shulie.in
輸出文件:shulie.out
簡單對比時間限制:1 s 內存限制:160 MB
【問題描述】
假設有一列數 {Ai }(1 ≤ i ≤ n) ,支持如下兩種操作:
(1)將 A k 的值加 D 。( k, D 是輸入的數)
(2) 輸出 A s +A s+1 +…+A t 。( s, t 都是輸入的數, S ≤ T )
根據操作要求進行正確操作並輸出結果。
【輸入格式】
輸入文件第一行一個整數 n(0<=n<=100000) , 第二行爲 n 個整數,表示 {A i } 的初始值。
第三行爲一個整數 m(0<=m<=150000) ,表示操作數。 下接 m 行,每行描述一個操作,有如下兩種情況:
ADD k d ( 表示將 A k 加 d , 1<=k<=n , d 爲整數 )
SUM s t (表示輸出 A s +…+A t )
【輸出格式】
對於每一個 SUM 提問,輸出結果
【輸入輸出樣例】
輸入:
4
1 4 2 3
3
SUM 1 3
ADD 2 50
SUM 2 3
輸出:
7
56
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define MAX_N 100000
int n;
int num[MAX_N];
struct Node
{
int Sum;
int Delay;
Node *pLeft,*pRight;
};
void Init(Node **pNode,int Left,int Right)
{
Node *pNew=new Node;
if(Right-Left==1)
{
pNew->Delay=0;
pNew->Sum=num[Left];
pNew->pLeft=pNew->pRight=NULL;
}
else
{
int mid=(Right+Left)>>1;
pNew->Sum=0;
pNew->Delay=0;
Init(&pNew->pLeft,Left,mid);
Init(&pNew->pRight,mid,Right);
pNew->Sum=pNew->pLeft->Sum+pNew->pRight->Sum;
}
*pNode=pNew;
}
void Add(Node *pNode,int ID,int val,int Left,int Right)
{
if(Right-Left==1)
{
pNode->Sum+=val;
}
else
{
int mid=(Left+Right)>>1;
if(ID<mid)
{
Add(pNode->pLeft,ID,val,Left,mid);
}
else
{
Add(pNode->pRight,ID,val,mid,Right);
}
pNode->Sum=pNode->pLeft->Sum+pNode->pRight->Sum;
}
}
void Add(Node *pNode,int a,int b,int val,int Left,int Right)
{
if(a<=Left && Right>=b)
{
pNode->Sum+=val*(Right-Left);
pNode->Delay+=val;
}
else
{
int mid=(Right+Left)>>1;
if(pNode->Delay)
{
pNode->pLeft->Sum+=pNode->Delay*(mid-Left);
pNode->pLeft->Delay+=pNode->Delay;
pNode->pRight->Sum+=pNode->Delay*(Right-mid);
pNode->pRight->Delay+=pNode->Delay;
pNode->Delay=0;
}
if(a<mid)
Add(pNode->pLeft,a,b,val,Left,mid);
if(b>mid)
Add(pNode->pRight,a,b,val,mid,Right);
pNode->Sum=pNode->pLeft->Sum+pNode->pRight->Sum;
}
}
int Sum(Node *pNode,int a,int b,int Left,int Right)
{
if(a<=Left && Right<=b)
{
return pNode->Sum;
}
else
{
int s1=0,s2=0;
int mid=(Left+Right)>>1;
if(a<mid)
s1=Sum(pNode->pLeft,a,b,Left,mid);
if(b>mid)
s2=Sum(pNode->pRight,a,b,mid,Right);
return s1+s2;
}
}
int Sum2(Node *pNode,int a,int b,int Left,int Right)
{
if(a<=Left && Right<=b)
{
return pNode->Sum;
}
else
{
int s1=0,s2=0;
int mid=(Left+Right)>>1;
if(pNode->Delay)
{
pNode->pLeft->Sum+=pNode->Delay*(mid-Left);
pNode->pLeft->Delay+=pNode->Delay;
pNode->pRight->Sum+=pNode->Delay*(Right-mid);
pNode->pRight->Delay+=pNode->Delay;
pNode->Delay=0;
}
if(a<mid)
s1=Sum2(pNode->pLeft,a,b,Left,mid);
if(b>mid)
s2=Sum2(pNode->pRight,a,b,mid,Right);
return s1+s2;
}
}
int main()
{
freopen("shulie.in","r",stdin);
freopen("shulie.out","w",stdout);
Node *pNode;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&num[i]);
if(n==0) return 0;
Init(&pNode,0,n);
int m;
scanf("%d",&m);
char words[8];
for(int i=0;i<m;i++)
{
int a,b;
scanf("%s%d%d",words,&a,&b);
if(!strcmp(words,"SUM"))
{
printf("%d\n",Sum(pNode,a-1,b,0,n));
}
else
{
Add(pNode,a-1,b,0,n);
}
}
return 0;
}