- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 62 lines of C++ from the credited upstream file yosupo-stern-brocot-tree.test.cpp.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1#define PROBLEM "https://judge.yosupo.jp/problem/stern_brocot_tree"23#include "../../template/template.hpp"45#include "../../math/stern-brocot-tree.hpp"6 7using namespace Nyaan;8 9using SBT = SternBrocotTreeNode<ll>;10 11void q() {12 ins(cmd);13 if (cmd == "DECODE_PATH") {14 ini(n);15 SBT f;16 rep(_, n) {17 char c;18 in(c);19 inl(x);20 if (c == 'R') f.go_right(x);21 if (c == 'L') f.go_left(x);22 }23 out(f.x, f.y);24 } else if (cmd == "ENCODE_PATH") {25 inl(x, y);26 SBT f{x, y};27 cout << f.seq.size() << " ";28 each(s, f.seq) {29 cout << (s > 0 ? 'R' : 'L') << " ";30 cout << abs(s) << " ";31 }32 cout << "\n";33 } else if (cmd == "LCA") {34 inl(x1, y1, x2, y2);35 SBT f{x1, y1}, g{x2, y2};36 SBT h = SBT::lca(f, g);37 out(h.x, h.y);38 } else if (cmd == "ANCESTOR") {39 inl(k, x, y);40 SBT f{x, y};41 42 ll l = f.depth() - k;43 if (l < 0) {44 out(-1);45 } else {46 bool b = f.go_parent(l);47 assert(b == true);48 out(f.x, f.y);49 }50 } else {51 inl(x, y);52 SBT f{x, y};53 out(f.lower_bound(), f.upper_bound());54 }55}56 57void Nyaan::solve() {58 int t = 1;59 in(t);60 while (t--) q();61}62