add segtree snippet

This commit is contained in:
Code Lich 2025-04-14 10:22:51 +07:00
parent aae1a8631d
commit ae7968f066
1 changed files with 44 additions and 0 deletions

View File

@ -25,6 +25,50 @@ ls.add_snippets('cpp', {
'}', '}',
}, },
}), }),
s('segtree', {
t {
'struct SegTree {',
' int n;',
' vector<int> tree;',
'',
' inline int combine(int a, int b) {',
' // TODO: chỉnh sửa hàm combine cho phù hợp (vd: min(a, b), max(a, b), a + b, ...)',
' return a + b;',
' }',
'',
' SegTree(const vector<int> &arr) {',
' n = arr.size();',
' tree.resize(n << 1);',
' for (int i = 0; i < n; ++i)',
' tree[i + n] = arr[i];',
' for (int i = n - 1; i > 0; --i)',
' tree[i] = combine(tree[i << 1], tree[i << 1 | 1]);',
' }',
'',
' inline void update(int pos, int val) {',
' pos += n;',
' tree[pos] = val;',
' for (pos >>= 1; pos; pos >>= 1)',
' tree[pos] = combine(tree[pos << 1], tree[pos << 1 | 1]);',
' }',
'',
' inline int query(int l, int r) {',
' int resL = 0, resR = 0; // TODO: chỉnh phần tử đơn vị phù hợp',
' l += n;',
' r += n;',
' while (l < r) {',
' if (l & 1)',
' resL = combine(resL, tree[l++]);',
' if (r & 1)',
' resR = combine(tree[--r], resR);',
' l >>= 1;',
' r >>= 1;',
' }',
' return combine(resL, resR);',
' }',
'};',
},
}),
s('binpow', { s('binpow', {
t { t {
'll binpow(ll a, ll b, ll c) {', 'll binpow(ll a, ll b, ll c) {',