参考链接线段树从入门到进阶
以下是我在洛谷中对应题目的AC代码
#include
#include
#include
using namespace std;
struct Node {
int sum;
int l,r;
};
void build_tree(int i, int l, int r, vector<Node>& node, vector<int>& arr) {
node[i].l = l;
node[i].r = r;
if (l == r) {
node[i].sum = arr[l];
return;
}
int mid = (l + r) >> 1;
build_tree(2 * i, l, mid, node, arr);
build_tree(2 * i + 1, mid + 1, r, node, arr);
}
void modify_region(int i, int l, int r, int add, vector<Node>& node) {
if (node[i].l >= l && node[i].r <= r) {
node[i].sum += add;
return;
}
if (node[2*i].r >= l) modify_region(2*i, l, r, add, node);
if (node[2*i+1].l <= r) modify_region(2*i+1, l, r, add, node);
}
int get_single_num(int i, int index, vector<Node>& node) {
int sum = node[i].sum;
if (node[i].l == node[i].r) return sum;
if (node[2*i].r >= index) sum += get_single_num(2*i, index, node);
else sum += get_single_num(2*i+1, index, node);
return sum;
}
int main() {
int n,m;
scanf("%d %d", &n, &m);
vector<int> arr(n+1);
for (int i = 1; i <= n; ++i) {
scanf("%d", &arr[i]);
}
vector<Node> node(4*n+2);
//build tree
build_tree(1, 1, n, node, arr);
int op, left, right, add, index;
for (int i = 0; i < m; ++i) {
scanf("%d", &op);
if (op == 1) {
scanf("%d %d %d", &left, &right, &add);
modify_region(1, left, right, add, node);
}
else {
scanf("%d", &index);
printf("%d\n", get_single_num(1, index, node));
}
}
return 0;
}
#include
#include
#include
using namespace std;
struct Node {
int sum;
int l,r;
};
void build_tree(int i, int l, int r, vector<Node>& node, vector<int>& arr) {
node[i].l = l;
node[i].r = r;
if (l == r) {
//cout << "node " << i << ' ' << arr[l] << endl;
node[i].sum = arr[l];
return;
}
int mid = (l + r) >> 1;
build_tree(2 * i, l, mid, node, arr);
build_tree(2 * i + 1, mid + 1, r, node, arr);
node[i].sum = node[2*i].sum + node[2*i+1].sum;
}
void modify_single_point(int i, int index, int add, vector<Node>& node) {
node[i].sum += add;
if (node[i].l == node[i].r) {
return;
}
if (node[2*i].r >= index) modify_single_point(2*i, index, add, node);
else modify_single_point(2*i+1, index, add, node);
}
int get_sum(int i, int l, int r, vector<Node>& node) {
if (node[i].l >= l && node[i].r <= r) return node[i].sum;
if (node[i].l > r || node[i].r < l) return 0;
int sum = 0;
if (node[2*i].r >= l) sum += get_sum(2*i, l, r, node);
if (node[2*i+1].l <= r) sum += get_sum(2*i+1, l, r, node);
return sum;
}
int main() {
int n,m;
scanf("%d %d", &n, &m);
vector<int> arr(n+1);
for (int i = 1; i <= n; ++i) {
scanf("%d", &arr[i]);
}
vector<Node> node(4*n+2);
//build tree
build_tree(1, 1, n, node, arr);
int op, index, add;
for (int i = 0; i < m; ++i) {
scanf("%d %d %d", &op, &index, &add);
if (op == 1) {
modify_single_point(1, index, add, node);
}
else {
//sum
printf("%d\n", get_sum(1, index, add,node));
}
}
return 0;
}