- 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
- 87 lines of C++ from the credited upstream file network-recovery-pathways.cpp.
- The implementation visibly relies on sequence storage.
- 12 loop blocks 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.
123 45class Solution {6public:7 int findMaxPathScore(vector<vector<int>>& edges, vector<bool>& online, long long k) {8 static const auto INF = numeric_limits<int64_t>::max();9 10 const auto& binary_search_right = [](auto left, auto right, const auto& check) {11 while (left <= right) {12 const auto mid = left + (right - left) / 2;13 if (!check(mid)) {14 right = mid - 1;15 } else {16 left = mid + 1;17 }18 }19 return right;20 };21 22 vector<vector<pair<int, int>>> adj(size(online));23 for (const auto& e : edges) {24 const int u = e[0], v = e[1], c = e[2];25 adj[u].emplace_back(v, c);26 }27 const auto& topological_sort = [&]() {28 vector<int> in_degree(size(adj));29 for (int u = 0; u < size(adj); ++u) {30 for (const auto& [v, _] : adj[u]) {31 ++in_degree[v];32 }33 }34 vector<int> q;35 for (int u = 0; u < size(adj); ++u) {36 if (!in_degree[u]) {37 q.emplace_back(u);38 }39 }40 vector<int> result;41 while (!empty(q)) {42 vector<int> new_q;43 for (const auto& u : q) {44 result.emplace_back(u);45 for (const auto& [v, _] : adj[u]) {46 --in_degree[v];47 if (in_degree[v]) {48 continue;49 }50 new_q.emplace_back(v);51 }52 }53 q = move(new_q);54 }55 return result;56 };57 58 const auto& order = topological_sort();59 const auto& check = [&](int x) {60 vector<int64_t> dist(size(adj), INF);61 dist[0] = 0;62 for (const auto& u : order) {63 if (dist[u] == INF) {64 continue;65 }66 for (const auto& [v, c] : adj[u]) {67 if (!(c >= x && online[v])) {68 continue;69 }70 dist[v] = min(dist[v], dist[u] + c);71 }72 }73 return dist.back() <= k;74 };75 76 int left = numeric_limits<int>::max(), right = 0;77 for (int u = 0; u < size(adj); ++u) {78 for (const auto& [_, c] : adj[u]) {79 left = min(left, c);80 right = max(right, c);81 }82 }83 const auto& result = binary_search_right(left, right, check);84 return result >= left ? result : -1;85 }86};87