线段树:
1584ms AC
#include
#include
int d[50010 << 2];
int sum;
void creat(int s,int t,int step)
{
if(s >= t)
{
scanf("%d",&d[step]);
return ;
}
int mid = (s + t) >> 1;
creat(s,mid,step << 1);
creat(mid + 1,t,step << 1 | 1);
d[step] = d[step << 1] + d[step << 1 | 1];
}
void upd(int s,int t,int us,int unum,int step)
{
if(s >= t)
{
d[step] += unum;
return ;
}
if(t < us || s > us)
return ;
int mid = (s + t) >> 1;
if(us <= mid)
upd(s,mid,us,unum,step << 1);
if(mid < us)
upd(mid + 1,t,us,unum,step << 1 | 1);
d[step] = d[step << 1] + d[step << 1 | 1];
}
void qu(int s,int t,int qs,int qt,int step)
{
if(s > qt || t < qs)
return ;
if(qs <= s && t <= qt)
{
sum += d[step];
return ;
}
int mid = (s + t) >> 1;
if(mid >= qs)
qu(s,mid,qs,qt,step << 1);
if(mid < qt)
qu(mid + 1,t,qs,qt,step << 1 | 1);
}
int main()
{
int n,s,t,step,qs,qt,us,unum,c = 0;
char sr[10];
scanf("%d",&n);
while(n--)
{
printf("Case %d:\n",++c);
scanf("%d",&t);
s = 1;
step = 1;
creat(s,t,step);
while(scanf("%s",sr),strcmp(sr,"End"))
{
if(!strcmp(sr,"Add"))
{
scanf("%d%d",&us,&unum);
upd(s,t,us,unum,step);
}
else if(!strcmp(sr,"Sub"))
{
scanf("%d%d",&us,&unum);
upd(s,t,us,-unum,step);
}
else if(!strcmp("Query",sr))
{
scanf("%d%d",&qs,&qt);
sum = 0;
qu(s,t,qs,qt,step);
printf("%d\n",sum);
}
}
}
return 0;
}
374ms AC
#include
#include
int d[500010];
int lowbit(int x)
{
return x & (-x);
}
void add(int step,int m,int n)
{
while(step <= n)
{
d[step] += m;
step += lowbit(step);
}
}
int sum(int q)
{
int sm = 0;
while(q > 0)
{
sm += d[q];
q -= lowbit(q);
}
return sm;
}
int main()
{
int n,t,us,unum,qs,qt,m,c = 0;
char sr[10];
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",++c);
scanf("%d",&n);
memset(d,0,sizeof(d));
for(int i = 1;i <= n;i++)
{
scanf("%d",&m);
add(i,m,n);
}
while(scanf("%s",sr),strcmp(sr,"End"))
{
if(!strcmp("Add",sr))
{
scanf("%d%d",&us,&unum);
add(us,unum,n);
}
else if(!strcmp("Sub",sr))
{
scanf("%d%d",&us,&unum);
add(us,-unum,n);
}
else if(!strcmp("Query",sr))
{
scanf("%d%d",&qs,&qt);
printf("%d\n",sum(qt) - sum(qs - 1));
}
}
}
return 0;
}