-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
algo(dsa): lazy segment tree with sum query
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
template<typename T> | ||
class SegTreeLazy { | ||
private: | ||
int N; | ||
vector<T> seg, lzy; | ||
|
||
void down(int k, int l, int r) { | ||
seg[k] += (r - l + 1) * lzy[k]; | ||
if (l < r) { | ||
lzy[k << 1] += lzy[k]; | ||
lzy[k << 1 | 1] += lzy[k]; | ||
} | ||
lzy[k] = 0; | ||
} | ||
|
||
void update(int i, int j, int k, int l, int r, T v) { | ||
if (lzy[k]) down(k, l, r); | ||
if (i > r or j < l) return; | ||
if (i <= l and j >= r) { | ||
seg[k] += (r - l + 1) * v; | ||
if (l < r) { | ||
lzy[k << 1] += v; | ||
lzy[k << 1 | 1] += v; | ||
} | ||
return; | ||
} | ||
|
||
update(i, j, k << 1, l, (l + r) / 2, v); | ||
update(i, j, k << 1 | 1, (l + r) / 2 + 1, r, v); | ||
seg[k] = seg[k << 1] + seg[k << 1 | 1]; | ||
} | ||
|
||
T query(int i, int j, int k, int l, int r) { | ||
if (lzy[k]) down(k, l, r); | ||
if (i > r or j < l) return 0; | ||
if (i <= l and j >= r) return seg[k]; | ||
|
||
T lft = query(i, j, k << 1, l, (l + r) / 2); | ||
T rgt = query(i, j, k << 1 | 1, (l + r) / 2 + 1, r); | ||
return lft + rgt; | ||
} | ||
|
||
public: | ||
SegTreeLazy(int N) : N(N), seg(N << 2, 0), lzy(N << 2, 0) {} | ||
|
||
void update(int i, int j, T v) { update(i, j, 1, 0, N - 1, v); } | ||
|
||
T query(int i, int j) { return query(i, j, 1, 0, N - 1); } | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
\subsection{Segment Tree Lazy} | ||
|
||
Query (Range Sum): $O(\log N)$ | ||
|
||
Update (Sum Value): $O(\log N)$ |