poj3468 A Simple Problem with Integers
空间8220K 时间3344MS
瞻仰时间在1000ms内的神
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct node
{
__int64 L;
__int64 R;
node *left;
node *right;
__int64 sum;
__int64 inc;
};
__int64 ncount=0;
node tree[200010];
void buildtree(node *p,__int64 L,__int64 R)
{
p->inc=0;
p->sum=0;
p->L=L;
p->R=R;
if(L!=R)
{
ncount++;
p->left=tree+ncount;
ncount++;
p->right=tree+ncount;
buildtree(p->left,L,(L+R)/2);
buildtree(p->right,(L+R)/2+1,R);
}
}
void insert(node *p,__int64 i,__int64 val)
{
if((p->L)==i&&(p->R)==i)
{
(p->sum)+=val;
return;
}
p->sum+=val;
if(i<=(p->L+p->R)/2)
{
insert(p->left,i,val);
}
else
{
insert(p->right,i,val);
}
}
__int64 res;
void oper(node *p,__int64 L,__int64 R,__int64 c);
void query(node *p,__int64 L,__int64 R)
{
if(p->L==L&&p->R==R)
{
res+=(p->sum+(p->inc)*(R-L+1));
return;
}
__int64 mid=(p->L+p->R)/2;
p->sum+=(p->inc)*(p->R-p->L+1);
//(p->left->inc)+=(p->inc);
//(p->right->inc)+=(p->inc);
oper(p->left,p->L,(p->L+p->R)/2,p->inc);
oper(p->right,(p->L+p->R)/2+1,p->R,p->inc);
p->inc=0;
if(R<=mid)
{
query(p->left,L,R);
}
else if(L>=mid+1)
{
query(p->right,L,R);
}
else
{
query(p->left,L,mid);
query(p->right,mid+1,R);
}
}
void oper(node *p,__int64 L,__int64 R,__int64 c)
{
if(p->L==L&&p->R==R)
{
p->inc+=c;
return;
}
p->sum+=(R-L+1)*c;
if(R<=(p->L+p->R)/2)
{
oper(p->left,L,R,c);
}
else if(L>=((p->L+p->R)/2+1))
{
oper(p->right,L,R,c);
}
else
{
oper(p->left,L,(p->L+p->R)/2,c);
oper(p->right,(p->L+p->R)/2+1,R,c);
}
}
int main()
{
__int64 i;
__int64 n,q;
scanf("%I64d %I64d",&n,&q);
buildtree(tree,1,n);
__int64 temp;
for(i=1;i<=n;i++)
{
scanf("%I64d",&temp);
insert(tree,i,temp);
}
getchar();
char ch;
__int64 L,R,c;
for(i=0;i<q;i++)
{
scanf("%c",&ch);
if(ch=='Q')
{
scanf("%I64d %I64d",&L,&R);
res=0;
query(tree,L,R);
printf("%I64d\n",res);
}
if(ch=='C')
{
scanf("%I64d %I64d %I64d",&L,&R,&c);
oper(tree,L,R,c);
}
getchar();
}
return 0;
}