线段树 :区间修改,区间查询
Posted liuzz-20180701
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线段树 :区间修改,区间查询相关的知识,希望对你有一定的参考价值。
题目描述
思路
代码
#include <cstdio>
#include <cstring>
long long n, m;
struct
long long at[1000005], arr[1000005 << 2], ad[1000005 << 2];
void build(int k, int l, int r)
if (l == r)
arr[k] = at[l];
return;
int mid = l + r >> 1;
this->build(k << 1, l, mid);
this->build(k << 1 | 1, mid + 1, r);
arr[k] = arr[k << 1] + arr[k << 1 | 1];
void change(int k, int l, int r, int x, int y, int v)
if (x <= l && r <= y)
this->add(k, l, r, v);
return;
int mid = l + r >> 1;
this->pushdown(k, l, r, mid);
if (x <= mid) this->change(k << 1, l, mid, x, y, v);
if (y > mid) this->change(k << 1 | 1, mid + 1, r, x, y, v);
arr[k] = arr[k << 1] + arr[k << 1 | 1];
long long query(int k, int l, int r, int x, int y)
if (x <= l && r <= y) return arr[k];
long long res = 0;
int mid = l + r >> 1;
this->pushdown(k, l, r, mid);
if (x <= mid) res += this->query(k << 1, l, mid, x, y);
if (y > mid) res += this->query(k << 1 | 1, mid + 1, r, x, y);
return res;
void add(int k, int l, int r, int v)
ad[k] += v;
arr[k] += (long long)(r - l + 1) * v;
void pushdown(int k, int l, int r, int mid)
if (ad[k] == 0) return;
add(k << 1, l, mid, ad[k]);
add(k << 1 | 1, mid + 1, r, ad[k]);
ad[k] = 0;
t;
inline long long read()
long long s = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
if (ch == '-') f = -1;
ch = getchar();
while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
int main()
n = read(), m = read();
for (register int i = 1; i <= n; ++i) t.at[i] = read();
t.build(1, 1, n);
for (register int i = 1, a, b, c, d; i <= m; ++i)
a = read();
if (a == 1)
b = read(), c = read(), d = read();
t.change(1, 1, n, b, c, d);
else
b = read(), c = read();
printf("%lld\n", t.query(1, 1, n, b, c));
return 0;
以上是关于线段树 :区间修改,区间查询的主要内容,如果未能解决你的问题,请参考以下文章