AC代码:
#include
using namespace std;
struct CNode
{
int L,R;
CNode *pLeft,*pRight;
long long nSum;//原来的和
long long lnc;//增量c的累加
};
CNode Tree[200010];//两倍叶子节点数目就足够
int nCount=0;
int Mid(CNode *pRoot)
{
return (pRoot->L+pRoot->R)/2;
}
void BuildTree(CNode *pRoot,int L,int R)
{
pRoot->L=L;
pRoot->R=R;
pRoot->nSum=0;
pRoot->lnc=0;
if(L==R)
return;
nCount++;
pRoot->pLeft=Tree+nCount;
nCount++;
pRoot->pRight=Tree+nCount;
BuildTree(pRoot->pLeft,L,(L+R)/2);
BuildTree(pRoot->pRight,(L+R)/2+1,R);
}
void Insert(CNode *pRoot,int i,int v)
{
if(pRoot->L==i&&pRoot->R==i)
{
pRoot->nSum=v;
return;
}
pRoot->nSum+=v;
if(i<=Mid(pRoot))
Insert(pRoot->pLeft,i,v);
else
Insert(pRoot->pRight,i,v);
}
//添加的规律:找到终节点前计算(或更新)nSum,仅在终结点(完全属于所加区间的节点)加c
//即是,更新nSum的没有更新C(但nSum是更新后的值),更新C的没有更新nSum;
void Add(CNode *pRoot,int a,int b,long long c)
{
if(pRoot->L==a&&pRoot->R==b)
{
pRoot->lnc+=c;
return;
}
pRoot->nSum+=c*(b-a+1);
if(b<=(pRoot->L+pRoot->R)/2)
Add(pRoot->pLeft,a,b,c);
else if(a>=(pRoot->L+pRoot->R)/2+1)
Add(pRoot->pRight,a,b,c);
else
{
Add(pRoot->pLeft,a,(pRoot->L+pRoot->R)/2,c);
Add(pRoot->pRight,(pRoot->L+pRoot->R)/2+1,b,c);
}
}
long long QuerynSum(CNode *pRoot,int a,int b)
{
if(pRoot->L==a&&pRoot->R==b)
{
//终节点仅计算和,不对c进行下一级更新
return pRoot->nSum+(pRoot->R-pRoot->L+1)*pRoot->lnc;
}
//算好非终节点的nSum之后,更新后面的增量c,将本节点的增量清0
pRoot->nSum+=(pRoot->R-pRoot->L+1)*pRoot->lnc;
Add(pRoot->pLeft,pRoot->L,Mid(pRoot),pRoot->lnc);
Add(pRoot->pRight,Mid(pRoot)+1,pRoot->R,pRoot->lnc);
pRoot->lnc=0;
if(b<=Mid(pRoot))
return QuerynSum(pRoot->pLeft,a,b);
else if(a>=Mid(pRoot)+1)
return QuerynSum(pRoot->pRight,a,b);
else{
return QuerynSum(pRoot->pLeft,a,Mid(pRoot))+
QuerynSum(pRoot->pRight,Mid(pRoot)+1,b);
}
}
int main()
{
int n,q,a,b,c;
char cmd[10];
scanf("%d %d",&n,&q);
int i,j,k;
nCount=0;
BuildTree(Tree,1,n);
for(i=1;i<=n;i++)
{
scanf("%d",&a);
Insert(Tree,i,a);
}
for(i=0;i