题意分析:
这道题的题意很容易理解,而且这道题考察的知识点也很明了,如果对线段树或者树状数组了解的话,这道题大家都能写出来代码。这道题它唯一坑爹的地方是输入是scanf,输出是printf.表示太坑了。
代码如下:
用树状数组代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[50010],c[50010];
int lowbit(int x) {
return x&(-x);
}
int getsum(int x) {
int sum=0;
while(x>0) {
sum+=c[x];
x-=lowbit(x);
}
return sum;
}
void add(int x,int b,int& n) {
while(x<=n) {
c[x]+=b;
x+=lowbit(x);
}
}
void sub(int x,int b,int& n) {
while(x<=n) {
c[x]-=b;
x+=lowbit(x);
}
}
int main() {
int t,n,st,en,i,k=1;
scanf("%d",&t);
while(t--) {
memset(c,0,sizeof(c));
scanf("%d",&n);
for(i=1; i<=n; i++) {
scanf("%d",&a[i]);
add(i,a[i],n);
}
//cout<<getsum(3)<<' '<<getsum(5)<<endl;
char s[10];
printf("Case %d:\n",k++);
while(scanf("%s",s) &&strcmp(s,"End")) {
scanf("%d%d",&st,&en);
if(strcmp(s,"Query")==0) {
printf("%d\n",getsum(en)-getsum(st-1));
}
else if(strcmp(s,"Add")==0) {
add(st,en,n);
}
else if(strcmp(s,"Sub")==0) {
sub(st,en,n);
}
}
}
return 0;
}
用线段树代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node{
int lc;
int rc;
int sum;
}s[200000];
void build(int lc,int rc,int k) {
if(lc == rc) {
s[k].lc = lc;
s[k].rc = rc;
s[k].sum=0;
return ;
}
int mid=(lc+rc)>>1;
s[k].lc = lc;
s[k].rc = rc;
build(lc,mid,2*k);
build(mid+1,rc,2*k+1);
s[k].sum=0;
}
void insert(int val,int index,int k) {
if(s[k].lc == s[k].rc) {
s[k].sum+=val;
return ;
}
int mid=(s[k].lc+s[k].rc)>>1;
if(index<=mid) insert(val,index,2*k);
else insert(val,index,2*k+1);
s[k].sum=s[2*k].sum+s[2*k+1].sum;
}
int ans=0;
void search(int lc,int rc,int k) {
if(lc==s[k].lc && rc == s[k].rc) {
ans+=s[k].sum;
return ;
}
int mid=(s[k].lc+s[k].rc)>>1;
if(rc<=mid) search(lc,rc,2*k);
else if(lc>mid) search(lc,rc,2*k+1);
else {
search(lc,mid,2*k);
search(mid+1,rc,2*k+1);
}
}
int main() {
int t,co,a,b,i,j,n;
char str[10];
scanf("%d",&t);
for(j=1; j<=t; j++) {
cout<<"Case "<<j<<":"<<endl;
cin>>n;
build(1,n,1);
for(i=1; i<=n; i++) {
scanf("%d",&a);;
insert(a,i,1);
}
//cout<<a<<endl;
while(scanf("%s",str) &&strcmp(str,"End")) {
scanf("%d%d",&a,&b);
if(strcmp(str,"Query")==0) {
ans=0;
search(a,b,1);
cout<<ans<<endl;
}
else if(strcmp(str,"Add")==0) {
insert(b,a,1);
}
else if(strcmp(str,"Sub")==0) {
insert(-b,a,1);
}
}
}
return 0;
}