标签:
Regular segment tree usage. Should be medium though.
struct Node { Node(int rs, int re) : s(rs), e(re), left(nullptr), right(nullptr){} int s; int e; long long sum; Node *left; Node *right; }; class Solution { Node *root; public: /** * @param A: An integer vector */ Node * _build(int s, int e, vector<int> &A) { if(s > e) return nullptr; Node *p = new Node(s, e); if(s == e) { p->sum = A[s]; return p; } int mid = (s + e) / 2; p->left = _build(s, mid, A); p->right= _build(mid+1, e, A); p->sum = p->left->sum + p->right->sum; return p; } Solution(vector<int> A) { root = _build(0, A.size() - 1, A); } /** * @param start, end: Indices * @return: The sum from start to end */ long long _query(Node *p, int start, int end) { if(start == p->s && end == p->e) { return p->sum; } int mid = (p->s + p->e) / 2; if(end <= mid) { return _query(p->left, start, end); } else if(start > mid) { return _query(p->right, start, end); } long long rl = _query(p->left, start, mid); long long rr = _query(p->right,mid+1, end); return rl + rr; } long long query(int start, int end) { return _query(root, start, end); } /** * @param index, value: modify A[index] to value. */ int _modify(Node *p, int i, int val) { if(p->s == p->e && i == p->s) { int d = val - p->sum; p->sum = val; return d; } int mid = (p->s + p->e) / 2; int d = 0; if (i <= mid) { d = _modify(p->left, i, val); } else { d = _modify(p->right,i, val); } p->sum += d; return d; } void modify(int index, int value) { _modify(root, index, value); } };
标签:
原文地址:http://www.cnblogs.com/tonix/p/4894788.html