Download presentation
Presentation is loading. Please wait.
Published byBryan Shepherd Modified over 9 years ago
1
Binary Search From solving a problem to verifying an answer
2
Problems using Binary Search Finding a minimum or a maximum value. Change problem from “What is the optimal value?” to “Is optimal less than or equal to X?” Auxiliary function to check if a value to the answer satisfies the problem’s constraints. Answer to “Does value X work as a (not necessarily optimal) answer?” must be distributed as below: (all true followed by all false or vice versa) True True True True True True True True False False False False False False False True True True True True
3
Code f(x) returns true if x is valid answer, false if it is not Find minimum answer Find maximum answer lo will be optimal answer. If f(lo) = false then there is no solution (f is false for all x). while(lo < hi) { mid = lo + (hi-lo)/2; // reduces to (lo+hi)/2 if lo > 0 if( f(x) ) hi = mid; else lo = mid + 1; } while(lo < hi) { mid = lo + (hi-lo+1)/2; // reduces to (lo+hi+1)/2 if lo > 0 if( f(x) ) lo = mid; else hi = mid - 1; }
4
Example 1: Shortest Path Given a directed graph with source A and destination B, find a path that minimizes the maximum edge. Binary Search on the maximum edge weight. Let X be the maximum edge’s value. Delete all edges with weight > X. X works if there is a path from A to B in this graph. Can also be solved using a variant of Dijkstra or a minimum spanning tree.
5
Example 2: Crates You have N books, each with width W_i. You can use at most M crates, and each must have the same width. What’s the smallest width each crate can have if you want to fit in all N books in order? Binary Search on the crate width. Let X be the crate width, and fill books into each crate in the order they are listed. If it requires more than M crates, X is invalid. Otherwise, it is valid.
6
Example 3: More Paths What’s the shortest path between A and B if you are allowed to delete any K edges from the graph, where the path length is the maximum edge weight along the path? Binary Search on the maximum edge weight. Let X be the maximum edge’s value. Set the distance of all edges with weight > X to 1 and all other edge weights to 0. X works if the distance between A and B is X).
7
Problem of the week Farmer John is ranking his N cows. He has decided to rank the cows two at a time, and he may rank cows more than once. He has compiled a list of M decisions A > B, meaning cow A is better than cow B. Find the earliest point in his list where there is a contradiction (such that no sequence of cows satisfies the constraints). 2<=N, M<=10: 10 pts 2<=N, M<=1,000: 15 pts 2<=N, M<=100,000: 25 pts
8
Problem of the week Input format Line 1: Two integers, N and M Line 2…M+1: A B, meaning cow A > cow B Output: Index of earliest contradiction, or -1 if none exist. Sample input 4 5 1 2 2 4 3 4 4 1 1 3 Sample output 4
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.