PrevNext
Has Not Appeared
 0/4

Parallel Binary Search

Author: Muaath Alqarni

Answer binary search queries offline

Edit This Page

Prerequisites

Resources

Tutorial

This technique is usually used when we can solve a single query by doing linear or binary search on monotonic function.

The trick is doing it offline, sort queries by their median (initially ll, rr will be the binary search values), do linear search, whenever you find a query its median in same as your position in linear search, check the monotonic function, and do same as binary search (edit either ll or rr).

You will need to do the linear search O(log2N)O(\log_2{N}) times, so l=rl = r.

Usually the complexity would be: O((N+Q)log2(N+Q)2)O((N+Q) \cdot \log_2{(N+Q)}^2)

Focus Problem – try your best to solve this problem before continuing!

View Internal Solution

Solution - New Roads Queries

We can see that connectivity of the nodes is a monotonic function.

Now let's use parallel binary search:

When sweeping through the array of edges, union them in the DSU.

Whenever there is a query with median = ii, if the two nodes where connected in DSU, it means the answer is i\leq i (r=ir = i), otherwise it means >i\gt i (l=i+1l = i+1).

Total Complexity: O((N+Q)log2(N+Q)2α(N))O((N+Q) \cdot \log_2(N+Q)^2 \cdot \alpha{(N)}), α(N)\alpha{(N)} is for the DSU.

Implementation - New Roads Queries

C++

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 1;
struct DSU {
int cnt[N], par[N];
void Init(int sz) {
for (int i = 0; i <= sz; i++) par[i] = i, cnt[i] = 1;
}

Problems

StatusSourceProblem NameDifficultyTags
HREasy
Show TagsDSU, PBS
ACEasy
Show TagsDSU, PBS
COCINormal
Show TagsPBS, Segtree

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext