Parallel Binary Search
Author: Muaath Alqarni
Answer binary search queries offline
Prerequisites
- Silver - Binary Search
- Divide & Conquer
Resources
Resources | ||||
---|---|---|---|---|
CF | ||||
SPBook |
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 , 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 or ).
You will need to do the linear search times, so .
Usually the complexity would be:
Focus Problem – try your best to solve this problem before continuing!
View Internal SolutionSolution - 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 = , if the two nodes where connected in DSU, it means the answer is (), otherwise it means ().
Total Complexity: , 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
Status | Source | Problem Name | Difficulty | Tags | |
---|---|---|---|---|---|
HR | Easy | Show TagsDSU, PBS | |||
AC | Easy | Show TagsDSU, PBS | |||
COCI | Normal | 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!