这段代码有什么问题并纠正:#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<stdio.h> using namespace std; const int MAXN = 50010; int T, N; int a[MAXN], tree[MAXN*4]; void build(int node, int l, int r) { if (l == r) { sum[node] = a[r]; return; } int mid = (r - l) / 2 + l; build(node * 2, l, mid); build(node * 2 + 1, mid + 1, r); sum[node] = sum[node * 2] + sum[node * 2 + 1]; } void update(int node, int l, int r, int x, int v) { if (l == r) { sum[node] += v; return; } int mid = (l + r) >> 1; if (x <= mid) update(node * 2, l, mid, x, v); else update(node * 2 + 1, mid + 1, r, x, v); sum[node] = sum[node * 2] + sum[node * 2 + 1]; } int query(int node, int l, int r, int ql, int qr) { if (ql <= l && qr >= r) return sum[node]; int mid = (l + r) >> 1, res = 0; if (ql <= mid) res += query(node * 2, l, mid, ql, qr); if (qr > mid) res += query(node * 2 + 1, mid + 1, r, ql, qr); return res; } int main() { int T,n=0; cin >> T; while(T--){ int N; cin >> N; n++; cout << "Case " << n << ":" << endl; for (int i = 1; i <= N; ++i) { cin >> a[i]; } build(1, 1, N); char op[5]; while (1) { cin >> op; if (op[0] == 'E') break; if (op[0] == 'A') { int x, i; cin >> x >> i; update(1, 1, N, i, x); } else if (op[0] == 'S') { int x, i; cin >> x >> i; update(1, 1, N, i, -x); } else { int i, j; cin >> i >> j; printf("%d\n", query(1, 1, N, i, j)); } } } return 0; }
时间: 2024-02-14 18:13:57 浏览: 140
C++ 中pragma once 与 #ifndef _XXX_H_ #define _XXX_H_的区别
5星 · 资源好评率100%
有两个问题:
1. 在函数 build 中,变量名 sum 是未定义的;
2. 在主函数中,已经定义了全局变量 T,但在 while 循环中又重新定义了局部变量 T。
纠正后的代码如下:
```cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stdio.h>
using namespace std;
const int MAXN = 50010;
int T, N;
int a[MAXN], sum[MAXN*4];
void build(int node, int l, int r) {
if (l == r) {
sum[node] = a[r];
return;
}
int mid = (r - l) / 2 + l;
build(node * 2, l, mid);
build(node * 2 + 1, mid + 1, r);
sum[node] = sum[node * 2] + sum[node * 2 + 1];
}
void update(int node, int l, int r, int x, int v) {
if (l == r) {
sum[node] += v;
return;
}
int mid = (l + r) >> 1;
if (x <= mid)
update(node * 2, l, mid, x, v);
else
update(node * 2 + 1, mid + 1, r, x, v);
sum[node] = sum[node * 2] + sum[node * 2 + 1];
}
int query(int node, int l, int r, int ql, int qr) {
if (ql <= l && qr >= r)
return sum[node];
int mid = (l + r) >> 1, res = 0;
if (ql <= mid)
res += query(node * 2, l, mid, ql, qr);
if (qr > mid)
res += query(node * 2 + 1, mid + 1, r, ql, qr);
return res;
}
int main() {
cin >> T;
for (int n = 1; n <= T; ++n) {
cin >> N;
cout << "Case " << n << ":" << endl;
for (int i = 1; i <= N; ++i) {
cin >> a[i];
}
build(1, 1, N);
char op[5];
while (1) {
cin >> op;
if (op[0] == 'E') break;
if (op[0] == 'A') {
int x, i;
cin >> x >> i;
update(1, 1, N, i, x);
}
else if (op[0] == 'S') {
int x, i;
cin >> x >> i;
update(1, 1, N, i, -x);
}
else {
int i, j;
cin >> i >> j;
printf("%d\n", query(1, 1, N, i, j));
}
}
}
return 0;
}
```
阅读全文