Skip to content

Commit b20b54c

Browse files
committed
add seg tree walk
1 parent 0c0be65 commit b20b54c

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

library/data_structures_[l,r]/seg_tree.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,5 @@ template<class T, class F> struct tree {
3030
while (l <= r) x = op(x, s[nxt(l, r)]);
3131
return x;
3232
}
33+
#include "seg_tree_uncommon/walk.hpp"
3334
};
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
T walk(int l, int r, function<bool(T)> f) {
2+
for (l += n, r += n; l <= r;)
3+
if (int u = nxt(l, r); f(s[u])) {
4+
while (u < n)
5+
if (f(s[2 * u])) u = 2 * u;
6+
else u = 2 * u + 1;
7+
return u - n;
8+
}
9+
return -1;
10+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#define PROBLEM \
2+
"https://judge.yosupo.jp/problem/predecessor_problem"
3+
#include "../template.hpp"
4+
#include "../../../library/data_structures_[l,r]/seg_tree.hpp"
5+
int main() {
6+
cin.tie(0)->sync_with_stdio(0);
7+
int n, q;
8+
cin >> n >> q;
9+
string s;
10+
cin >> s;
11+
vector<int> init(n);
12+
for (int i = 0; i < n; i++) init[i] = s[i] - '0';
13+
tree st(init, plus<int>{});
14+
while (q--) {
15+
int type, k;
16+
cin >> type >> k;
17+
if (type == 0) {
18+
if (st.query(k, k) == 0) st.update(k, 1);
19+
} else if (type == 1) {
20+
if (st.query(k, k) == 1) st.update(k, 0);
21+
} else if (type == 2) {
22+
cout << st.query(k, k) << '\n';
23+
} else if (type == 3) {
24+
// returns first element in [k,n-1] such that sum > 0
25+
cout << st.walk(k, n - 1, [&](int sum) {
26+
return sum > 0;
27+
}) << '\n';
28+
} else {
29+
assert(type == 4);
30+
int total = st.query(0, k);
31+
if (total == 0) {
32+
cout << -1 << '\n';
33+
} else {
34+
int pref_sum = 0;
35+
cout << st.walk(0, k, [&](int sum) {
36+
if (pref_sum + sum == total) return 1;
37+
pref_sum += sum;
38+
return 0;
39+
}) << '\n';
40+
}
41+
}
42+
}
43+
return 0;
44+
}

0 commit comments

Comments
 (0)