简单记录一下自己的代码,以后方便复习
其实有了这样子的一个模板,题目变式自己改改就可以,比如说加减变成乘除等等。
#pragma GCC optimize(3,"Ofast","inline")
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define maxn 1000005
//#define true false
//#define false true
const int MaxN = 0x3f3f3f3f;
const int MinN = 0xc0c0c00c;
const double pi = acos(-1);
typedef long long ll;
const int mod = 1e9 + 7;
using namespace std;
ll arr[maxn];
ll tree[maxn];
ll add[maxn];
void build_tree(ll node, ll start, ll ends) {
if (start == ends) tree[node] = arr[start];
else {
ll mid = (start + ends) / 2;
build_tree(2 * node, start, mid);
build_tree(2 * node + 1, mid + 1, ends);
tree[node] = tree[2 * node] + tree[2 * node + 1];
}
}
void update_treepoint(ll node, ll start, ll ends, ll idx, ll val) { //单点修改
if (start == ends) {
arr[idx] = val;
tree[node] = val;
}
else {
ll mid = (start + ends) / 2;
if (idx >= start && idx <= mid) update_treepoint(2 * node, start, mid, idx, val);
else update_treepoint(2 * node+1, mid + 1, ends, idx, val);
tree[node] = tree[2 * node] + tree[2 * node+1];
}
}
void Add(ll node, ll start, ll ends, ll val) {
add[node] += val;
tree[node] += (ends - start + 1) * val;
return;
}
void pushdown(ll node, ll start, ll ends, ll mid) {
if (add[node] == 0) return;
Add(node * 2, start, mid, add[node]);
Add(node * 2 + 1, mid + 1, ends, add[node]);
add[node] = 0;
}
void update_section(ll node, ll start, ll ends, ll l, ll r, ll val) {
if (start >= l && ends <= r) return Add(node, start, ends, val);
ll mid = (start + ends) / 2;
pushdown(node, start, ends, mid);
if (l <= mid) update_section(node * 2, start, mid, l, r, val);
if (mid < r) update_section(node * 2 + 1, mid + 1, ends, l, r, val);
tree[node] = tree[node * 2] + tree[node * 2 + 1];
}
ll query_tree(ll node, ll start, ll ends, ll l, ll r) {
if (start >= l && ends <= r) return tree[node];
ll mid = (start + ends) / 2, ans = 0;
pushdown(node, start, ends, mid);
if (l <= mid) ans += query_tree(node * 2, start, mid, l, r);
if (r > mid) ans += query_tree(node * 2 + 1, mid + 1, ends, l, r);
return ans;
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) scanf("%lld", &arr[i]);
build_tree(1, 1, n);
ll flag;
while (m--) {
scanf("%lld", &flag);
ll l, r, val;
if (flag == 2) {
scanf("%lld%lld", &l, &r);
printf("%lld\n", query_tree(1, 1, n, l, r));
}
else {
scanf("%lld%lld%lld", &l, &r, &val);
update_section(1, 1, n, l, r, val);
}
}
return 0;
}