1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include<iostream>
using namespace std;
const int maxN = 101111;
int N, Q; int a[maxN];
class TreeNode { public: int l, r; long long tag, sum; TreeNode *lch, *rch; TreeNode(int l, int r): l(l), r(r) { tag = sum = 0; lch = rch = NULL; } void Add(long long x) { tag += x; sum += x * (r - l + 1); } void PushDown() { if (tag != 0) { lch->Add(tag); rch->Add(tag); tag = 0; } } void Update() { sum = lch->sum + rch->sum; } };
TreeNode* BuildTree(int* a, int l, int r) { TreeNode* v = new TreeNode(l, r); if (l == r) { v->sum = a[l]; return v; } int mid = (l + r) / 2; v->lch = BuildTree(a, l, mid); v->rch = BuildTree(a, mid + 1, r); v->Update(); return v; }
void Add(TreeNode* v, int l, int r, int x) { if (l <= v->l && v->r <= r) { v->Add(x); return; } v->PushDown(); int mid = (v->l + v->r) / 2; if (l <= mid) Add(v->lch, l, r, x); if (r > mid) Add(v->rch, l, r, x); v->Update(); }
long long GetSum(TreeNode* v, int l, int r) { if (l <= v->l && v->r <= r) return v->sum; v->PushDown(); int mid = (v->l + v->r) / 2; long long res = 0; if (l <= mid) res += GetSum(v->lch, l, r); if (r > mid) res += GetSum(v->rch, l, r); return res; }
void Work() { cin >> N >> Q; for (int i = 0; i < N; i++) scanf("%d", &a[i]); TreeNode* root = BuildTree(a, 0, N - 1); for (int i = 0; i < Q; i++) { char op = 0; while (op != 'C' && op != 'Q') op = getchar(); int l, r, x; scanf("%d %d", &l, &r); l--, r--; if (op == 'C') { scanf("%d", &x); Add(root, l, r, x); } else if (op == 'Q') { printf("%lld\n", GetSum(root, l, r)); } else throw "Invalid operation."; } }
int main() { Work(); return 0; }
|