本来用c++写的,结果超时了,后来把输入输出都改成了c的,就ac了
#include <stdio.h>
#include <string.h>
int num[50001];
char command[10];
typedef struct node node;
struct node
{
int l,r,person;
};
node numtree[200004];
void BuildTree(int t,int l,int r)
{
numtree[t].l = l;
numtree[t].r = r;
if(l == r)
{
numtree[t].person = num[l];
return ;
}
int mid = (l+r) >> 1;
BuildTree(t<<1, l, mid);
BuildTree(t<<1|1, mid+1, r);
numtree[t].person = numtree[t<<1].person + numtree[t<<1|1].person;
}
int QueryData(int t,int l,int r)
{
if(l == numtree[t].l && r == numtree[t].r)
return numtree[t].person;
int mid = (numtree[t].l + numtree[t].r) >> 1;
if(r <= mid)
return QueryData(t<<1, l, r);
else if(l > mid)
return QueryData(t<<1|1, l,r);
else
return (QueryData(t<<1, l, mid) + QueryData(t<<1|1, mid+1, r));
}
void Change(int t, int cur, int data)
{
if(numtree[t].l == numtree[t].r)
{
if(command[0] == 'A')
numtree[t].person += data;
else
numtree[t].person -= data;
return ;
}
int mid = (numtree[t].l + numtree[t].r) >>1;
if(cur <= mid)
Change(t<<1, cur, data);
else
Change(t<<1|1, cur, data);
numtree[t].person = numtree[t<<1].person + numtree[t<<1|1].person;
}
int main()
{
int T,time = 1,N;
scanf("%d",&T);
while(T--)
{
scanf("%d",&N);
for(int i = 1; i <= N; ++i)
scanf("%d",&num[i]);
BuildTree(1,1,N);
int a,b;
printf("Case %d:\n",time);
while(scanf(" %s",command) != EOF)
{
if(command[0] == 'E')
break;
else
{
scanf("%d %d",&a,&b);
if(command[0] == 'Q')
printf("%d\n",QueryData(1, a, b));
else if(command[0] == 'A' || command[0] == 'S')
Change(1, a, b);
}
}
++time;
}
return 0;
}
树状数组,忘了清空数组了,wa了好几发
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 50010;
string cmd;
int num[MAXN];
int N;
int lowBit(int x)
{
return x&-x;
}
int sum(int i)
{
int s = 0;
while(i > 0)
{
s += num[i];
i -= lowBit(i);
}
return s;
}
void add(int i, int x)
{
while(i <= N)
{
num[i] += x;
i += lowBit(i);
}
}
int main()
{
ios::sync_with_stdio(false);
int T,a,b,time = 0;
cin >> T;
while(T--)
{
memset(num,0,sizeof(num));
cin >> N;
for(int i = 1; i <= N; ++i)
{
cin >> a;
add(i,a);
}
cout << "Case " << ++time << ":" <<endl;
while(cin >> cmd && cmd != "End")
{
cin >> a >> b;
if(cmd == "Add")
{
add(a,b);
}
else if(cmd == "Sub")
{
add(a,-b);
}
else if(cmd == "Query")
{
cout << sum(b) - sum(a-1) << endl;
}
}
}
return 0;
}