Otion @ 2023-03-21 18:15:17
#include <iostream>
using namespace std;
const int N = (int)1e5 + 5;
int num[N];
struct node
{
int left;
int right;
int sum;
} nodes[4 * N];
int total_node;
int total_ask;
void push_up(int a)
{
nodes[a].sum = nodes[a << 1].sum + nodes[a * 2 + 1].sum;
return;
}
void build(int now, int left, int right)
{
if (left == right)
{
nodes[now] = {left, right, num[left]};
}
else
{
nodes[now] = {left, right};
int mid = nodes[now].left + nodes[now].right >> 1;
build(now << 1, left, mid);
build(now * 1 + 1, mid + 1, right);
push_up(now);
}
}
// int query(int now, int left, int right)
// {
// if (left <= nodes[now].left && right >= nodes[now].right)
// {
// return nodes[now].sum;
// }
// else
// {
// int sum = 0;
// int mid = nodes[now].left + nodes[now].right >> 1;
// if (left <= mid)
// {
// sum += query(now << 1, left, right);
// }
// if (right >= mid + 1)
// {
// sum += query(now << 1 | 1, left, right);
// }
// return sum;
// }
// }
int query(int u, int l, int r)
{
if (l <= nodes[u].left && nodes[u].right <= r)
return nodes[u].sum;
int mid = nodes[u].left + nodes[u].right >> 1;
int sum = 0; // 用 sum 来表示一下我们的总和
if (mid >= l)
sum += query(u << 1, l, r);
if (r >= mid + 1) // 看一下我们当前区间的中点和右边有没有交集
sum += query(u * 2 + 1, l, r);
return sum;
}
void modify(int now, int target, int demand)
{
if (nodes[now].left == nodes[now].right)
{
nodes[now].sum += demand;
return;
}
else
{
int mid = nodes[now].left + nodes[now].right >> 1;
if (target <= mid)
{
modify(now << 1, target, demand);
}
else
{
modify(now * 2 + 1, target, demand);
}
push_up(now);
}
}
int main()
{
cin >> total_node >> total_ask;
for (int i = 1; i <= total_node; i++)
{
cin >> num[i];
}
build(1, 1, total_node);
while (total_ask--)
{
int bind_1 = 0;
cin >> bind_1;
if (bind_1 == 1)
{
int bind_2, bind_3;
int bind_4;
cin >> bind_2 >> bind_3 >> bind_4;
for (int i = bind_2; i <= bind_3; i++)
{
modify(1, i, bind_4);
}
}
else
{
int bind_5, bind_6;
cin >> bind_5 >> bind_6;
int res = query(1, bind_5, bind_6);
cout << res << endl;
}
}
return 0;
}
by Otion @ 2023-03-21 18:30:40
擦,build里面应该是 now*2+1
手贱写错了