Pages

Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Jul 13, 2015

Be careful of implementing "binary search"

When using a binary search, we usually will calculate the middle of the search space by
mid = (start + end) / 2

However, if implement this calculation on a computer program, it might cause an overflow problem if the start and end are already too large. Therefore, instead of using (start + end) / 2, we could use
mid = start + (end - start) / 2


See more detail: http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

Mar 12, 2015

Apply BFS to special MST problems

Given a undirected and connected graph, and the edges have weights of either 1 or 2 (actually it is also applicable for weight larger than 2). How can we find a MST of the graph by using BFS?

Ans (I guess):
First, we can view an edge with weight of 2 as two edges with weight of 1 connected together. Then we can simply apply BFS to solve this problem. After finish the BFS algorithm, we check all the edges originally with weight of 2. If both parts of an edge are not both chosen as a path of the MST, then we delete this path. Finally, the result is a MST.