

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Solutions to tutorial problems on algorithms from the university of sydney's school of computer science. The problems cover topics such as graph algorithms (detecting cycles and finding minimum spanning trees), coin change, and prim's and dijkstra's algorithms. Students can use this document as a reference for understanding these concepts and for preparing exams, quizzes, or assignments.
Typology: Exercises
1 / 3
This page cannot be seen from the preview
Don't miss anything!


Algorithms Tutorial questions 2019 Semester 1 Tutorial 4
The University of Sydney School of Computer Science
Problem 1 Give an O(n) time algorithm to detect whether a given undirected graph contains a cycle. If the answer is yes, the algorithm should produce a cycle. (Assume adjacency list representation.)
Solution: We run DFS with a minor modification. Every time we scan the neighborhood of a vertex u we check if the neighbor v has been discovered before and whether it is different than u’s parent. If we can find such a vertex the we have our cycle: v, u, parent[u], parent[parent[u]],... , v. We only need to argue that this algorithm runs in O(n) time. Consider the execution of the algorithm up the point when we discovered the cycle. After the O(n) time spent initializing the arrays needed to run DFS, each call to dfs-visit takes time that is proportional to the edges discovered. However, up until the time we find the cycle we have only discovered tree edges. So the total number of edges is upper bounded by n − 1. Thus, the overall running time in O(n).
Problem 2 Find an amount for which the greedy coin change algorithm fails for the set of coins { 1 c, 10 c, 25 c}.
Solution: For 30c the greedy algorithm would choose 25c, 1 c, 1 c, 1 c, 1 c, 1 c (6 coins), but 10 c, 10 c, 10 c (3 coins) is more efficient.
Problem 3 Trace Prim’s algorithm on the graph in Fig. 1 starting at node a. What’s the output?
Solution: Recall Prim’s algorithm.
Step 0: Set a as the root, S = {a} and the tree T = nil.
Step 1: Find a lightest edge such that one endpoint is in S and the other is in V \ S. Add this edge to T and its (other) endpoint to S.
Step 2: If V \ S is empty then stop and output the minimum spanning tree T. Otherwise go to Step 1.
The output is shown in the below figure.
The red numbers show the order in which the nodes are added to the tree.
Problem 4 Trace Dikstra’s algorithm on the graph in Fig. 1 starting at node a and ending at g. What’s the shortest path?
Solution: The algorithm always choose to go to the node that is closest to the source. The output is shown below.
The red numbers show the length of the shortest path from a, and the blue numbers show the order in which the nodes are reached.