//A Simple Problem with Integers POJ - 3468
//线段树-区间修改-区间查询
#include <cstdio>
#define N 100010
typedef long long ll;
ll sum[N << 2];
ll lazy[N << 2];
ll x;
void push_up(int root) {
sum[root] = sum[root << 1] + sum[root << 1 | 1];
}
void push_down(int root, int len) {
if (lazy[root]) {
lazy[root << 1] += lazy[root];
lazy[root << 1 | 1] += lazy[root];
sum[root << 1] += lazy[root] * (len - (len >> 1));
sum[root << 1 | 1] += lazy[root] * (len >> 1);
lazy[root] = 0;
}
}
void buildTree(int l, int r, int root) {
lazy[root] = 0;
if (l == r) {
scanf("%lld", &x);
sum[root] = x;
return;
}
int mid = (l + r) >> 1;
buildTree(l, mid, root << 1);
buildTree(mid + 1, r, root << 1 | 1);
push_up(root);
}
/*
//单点修改
void updata(int k, int val, int l, int r, int root) {
if (l == k && r == k) {
sum[root] += val;
return;
}
int mid = (l + r) >> 1;
if (mid >= k) updata(k, val, l, mid, root << 1);
else updata(k, val, mid + 1, r, root << 1 | 1);
push_up(root);
}
*/
void updata(int L, int R, int val, int l, int r, int root) {
if (L <= l && r <= R) {
sum[root] += (ll) val * (r - l + 1);
lazy[root] += (ll) val;
return;
}
push_down(root, r - l + 1);
int mid = (l + r) >> 1;
if (L <= mid) updata(L, R, val, l, mid, root << 1);
if (mid < R) updata(L, R, val, mid + 1, r, root << 1 | 1);
push_up(root);
}
ll query(int L, int R, int l, int r, int root) {
if (L <= l && r <= R) {
return sum[root];
}
push_down(root, r - l + 1);
int mid = (l + r) >> 1;
ll ans = 0;
if (L <= mid) ans += query(L, R, l, mid, root << 1);
if (mid < R) ans += query(L, R, mid + 1, r, root << 1 | 1);
return ans;
}
int main() {
int n, q;
scanf("%d%d", &n, &q);
buildTree(1, n, 1);
while (q--) {
char ch[2];
int a, b, c;
scanf("%s", ch);
if (ch[0] == 'Q') {
scanf("%d%d", &a, &b);
printf("%lld\n", query(a, b, 1, n, 1));
} else {
scanf("%d%d%d", &a, &b, &c);
updata(a, b, c, 1, n, 1);
}
}
return 0;
}
A Simple Problem with Integers POJ - 3468(线段树 区间修改 区间查询)
最新推荐文章于 2020-10-06 22:28:23 发布