Assignment 04 - Prim 1_2_Queue (Solution)

# Assignment 04 - Prim 1_2_Queue (Solution) - O | V | | E |...

This preview shows page 1. Sign up to view the full content.

COMP 271: Design and Analysis of Algorithms Fall 2007 Solution to Assignment 4 Question 1 : Let G = ( V,E ) be a connected undirected graph in which all edges have weight 1 or 2. Give an O ( | V | + | E | ) algorithm to compute a minimum spanning tree of G. Justify the running time of your algorithm. (Hint: Modify Prim’s algorithm). Solution: This can be done in several ways. Here is a brief sketch of one solu- tion. Idea of the algorithm: ( 2 points ) Since all edges in the graph have weight 1 or 2, we can design a simple data structure so that “queue” operations such as Extract Min() and Decrease Key( u , newKey ) can be performed in O (1) time each, rather than O (log n ) time. By replacing the priority queue in Prim’s algo- rithm with this data structure, we reduce the time complexity to
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: O ( | V | + | E | ). Implementation Issue: ( 8 points ) We use two FIFO queues Q 1 and Q 2 to achieve the function of a priority queue. Q 1 contains items of weight 1 and Q 2 contains items of weight 2. • Operation Extract Min() can be done in O (1) time as follows: If Q 1 is not empty, dequeue the ±rst item from the front of Q 1 ; else if Q 1 is empty, dequeue the ±rst item from the front of Q 2 . • Operation Decrease Key( u , newKey ) can be done in O (1) time as fol-lows: If newKey is 2 (or 1), enqueue the element u to the rear of Q 2 (or Q 1 ). By replace the priority queue with the two FIFO queues, Prim’s algorithm can compute a MST of G in O ( | V | + | E | ) time. 1...
View Full Document

## This note was uploaded on 10/18/2009 for the course COMP 271 taught by Professor Arya during the Spring '07 term at HKUST.

Ask a homework question - tutors are online