This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentThis preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Page 1 of 9 COSC 2011 3.0 Fundamentals of Data Structures Solution of Final Exam
August 15, 2002; 19:00—22:00 1 Skip list [4) Consider the following skip list. 1
_ 0‘ ~m.l+/m+ '29 +0 Page 2 of9 2 AVL tree: removal (4)
Consider the following AVL tree. In the above AVL tree, the external nodes are not drawn. Forthemore, only the elements
(and not the keys) of the items are depicted. Draw the AVL thee after the node labelled E
has been removed and the tree has been restructured. 3 AVL tree: insertion (4) Consider the following subtree of a binary search tree. Tl"! Tin T“, Tm, Th, and T, are subtrees and n, n; and m,» are nodes. Before insertion of on item
into subtree Tm, the above tree was an AVL tree. After insertion, however, some of the
nodes of the tree have become onbotonced. {No rotations have been performed yet. ) Node n.
is the ﬁrst node on the path from the inserted node to the root of the tree that has become unbalanced. What is the balance factor of the node 11. before rotation? Motivate your answer
(use more than one sentence to eeptoin your answer). Page 3 of 9 Balance factor: 2 Motivotiori: Before the insertion, the node n was balanced, and hence its balance factor
was ml, 0 or 1. After insertion, the node n has become unbalanced and therefore its balance
factor has become smaller than 1 or greater than 1. Inserting an item into subtree 11,,
does not change the height of the subtree T, and increases the height of subtree rooted at m
by at most 1. Hence, the balance factor of it stayed the same or increased by 1. Therefore,
before insertion, the balance factor was 1 and after insertion it has become 2. 4 Scheduling courses (6) Courses and their prerequisite structure can be represented. as an. acyclic. directed simple
mph. The uertices represent the courses. There is a directed edge from one course to another
if the former course is a pmmquisits of the latter. Each vertex contains as its element the
name of the course it represents. The name of a course consists of four letters followed by four
numbers. The ﬁfth character determines the level of the course. For eeample, MATH I 0.90 is
a ﬁrst year course and 00302011 is a second year course. Consider the following algorithm. Algorithm schedule(graph, mom): (1) queue +— empty priority queue (2) for each vertex v of gmph do (3) incounteﬂu) (— indegree of o (4) if incouritedu) = 0 then (5) year +— 5th character of name of v
(6) insert item (year, 1;) into queue
(T) schedule 4— empty list (8) while queue is nonempty do (9) term 4— empty collection (10) while queue is nonempty A size of term < max do
(11) o + remove item with minimal key from queue
(12) add u to term (13) add term at the end of schedule (14) for each u in term do (15) for each outgoing edge (u, is) do (16) incounterﬁu) 4 incountedw) — 1 (17) if incountedw) = 0 then (18) year 1 5th character of name of w
(19) insert item (year, in) into queue (20) return schedule As input schedule takes an acyclic directed simple gmph graph, which represents the courses
and their prerequisite structures, and an integer more, which is the maximal number of courses
to be scheduled for each term. As output schedule produces a list of collections of cortices.
Each collection. represents the courses scheduled for a term. In the about: algorithm. lower level courses are. oiuen orioritu over hioher leuel courses. For Page 4 of 9 exempts, if mm: = 1 and for both 00302011 and BIOLIOIU att prerequisites have been me:
(their incounters are 0), then 310L101!) is chosen. The scheduting algorithm needs to be reﬁned such that for courses of the some level, the
MATH and 0030 courses have priority over the other courses. For example, assume
that alt prerequisites for MATHIDQU, BIOLIOIO and 003020.11 have been met. If mes
= 1 then MA THIOQO is. chosen. If max = 2 then MATHJOS'O and BIOLIOIO are chosen.
That is, MATHMQO has priority over BIOLIOIO (by topic) and BIOLI 01.0 has priority over
00502011 {by level). Describe how the above algorithm needs to be changed. {For example,
replace line (.9) with or insert between tine (5) and (6‘) ...) Replace line (5) and (6) with insert(v. queue) and replace line ('18) and (19) with inseam,
queue), where Algorithm insert(e, queue): year * ﬁth character of name of o if ﬁrst 4 characters of name of o are either 0086 or MATH then
priority +— 1 else
priority + 2 insert item ((year, priority), 11) into queue The keys of the priority queue queue are pairs of integers. They are ordered ”lesdcographically. 5 Huffman encoding (8) A Huﬁman code tree is a binary tree whose external nodes contain characters (and whose
internal nodes contain integers). A Huﬁman code word table is a dictionary with characters as keys and code words {strings of 0’sand I 's) as elements. From a Huﬁnan code tree one
can extract a Huﬁ'man code word table. For example, to the Huﬁ'man code tree corresponds the Huﬁrnan code word table character code word d 000
e 001
h 010
t 11 o 100
r 011 1;: 1m $33325on Give an algorithm/method that extracts from a Haﬁ'man code tree the corresponding Huﬂman
code word table. The worst case running time of your algorithm should be 0(a), where n
is the size of the Huffman code tree. You may use either pseudocode or Java code, that is, either complete the algorithm extract or complete the method extract. You may introduce
auzﬂz’ary algorithm/methods if needed. Algorithm extract(tnee, table): input: Hufﬂnan code tree; dictionary with characters as keys and bit strings as elements
postcondition: the (character, code word) pairs corresponding to the Huffman code tree
tree have been added to the dictionary table insert (character of root. of tree, “0”) into table
else extract(tree, “", table) Algorithm extractUree. preﬁx, table):
input: Huﬂman code tree; preﬁx of constructed code words; dictionary with characters as
keys and bit strings as elements
postcondition: the (character, code word) pairs corresponding to the Huﬁman code tree tree with the code word preﬁxed by preﬁx have been added to the dictionary table
if tree has a single node then insert (character of root of tree, preﬁx) into table
else extractﬂeft subtree of tree, preﬁx + “0". table)
extract(right subtree of tree, preﬁx + "1", table) fan * Adds to the specified dictionary the (character, code word) pairs =I= corresponding to the specified Huffman code tree.
* * @param tree Huffman code tree.
=1: opalam table dictionary with characters as keys and code words as elements
*/ public static void extract(Binarytree tree, Dictionary table) { if (tree.size{) == 1) {
table.insertItem(new Item(tree.root0.elementO, "0"));
}
else
extract£tree, tree.root(), "", table);
}
}
fan: * Adds to the specified dictionary the (character, code word) pairs
* corresponding to the specified Huffman code tree rooted at the specified Page 6 of9 at node. All constructed code words are prefixed with the specified prefix.
It * ﬁparam.tree Huffman code tree.
* @param node root of the subtree.
* @param prefix prefix of constructed code words.
* oparam table dictionary with characters as keys and code words as elements
*1
private static void extracﬂﬂinarytree tree, Position node,
String prefix, Dictionary table) {
if (tree.isExterna1(node))
{
table.insert1tem(neu Itemtnocleelemento, prefix”;
}
else
extract(tree, tree.leftChi1d(node), prefix + "0", table);
extracﬂtree, tree.rightChild(node), prefix + "1", table);
}
} 6 Connected components (6) Give an algorithm/method that computes the size of o smallest connected component of an
undirected simple graph. The worst case running time of your algorithm should be O(n+m),
where n is the number of uertices and m is the number of edges of the graph. You may use
either peeudooode or Java code, that is, either complete the algorithm sizeOmeaHeetCon
nectedComponent or complete the method sizeﬂmealleetConnectedComponent. You may
introduce auﬁtiam algorithms/methods if needed. Algorithm sizeOfSrnallectConnectedComponenﬂgmph):
input: undirected simple graph
output: size of a smallest connected component of graph
for each vertex vertex of graph do
colour vertex white
min +— 0
for each vertex vertex of graph do
if vertex is white then
min 4— min min DFS(verter, 0)
return min DFS(uertec, count):
colour vertex vertex black
for each edge incident on vertex do other 4— other endpoint of edge
if vertex other is whiter than PﬂEYNS count 4— DFS(ather, count)
return count + 1 fee Returns the size of a Smallest connected component of the specified
undirected simple graph. Qparam graph undirected simple graph.
Dreturn the size of a smallest connected component of the specified
undirected simple graph.
*/
public static int eizeDmeallestConnectedConponent(Graph graph)
{ ****** Iterator vertices = graph.vertices(); while (verticee.haeNext()) {
Decorablevertex vertex = (DecorableVertex) vertices.next();
vertex.aet(HHITE); } int min = 0; verticee = graph.vertices(); while (verticee.haeNext()) {
DecorableVertex vertex = (DecorableVertex) verticea.next();
if (vertex.get() == HHITE)
{
min = Math.min(min, DFS(vertex, 0));
}
}
return min; } private static int DFS(DecorableVertex vertex, int count) {
vertex.set(BLACK); Iterator adjacent = graph.adjacentVertices(vertex);
while (adjacent.hasNext()) {
DecorableVertex other = (DecorableVertex) adjacentnext():
if (other.get() == WHITE)
{
count = DFSCother, count);
}
} return Cmmt + 1 Payason } h colours of verticas *1‘
private static Object HHI'I'E
private static Object BLACK new DbjectO;
new Object 0: 7 Triangle test (8) Consider the following Java method that tests if an undirected simple graph has a triangle.
Such a graph has a triangle if there exist three diﬁemnt uertices, say u, v and w, such that
u and v, u and w, and v and w are adjacent. public static boolean hasTriangls(Graph graph)
{
boolean found = false;
Iterator vertices = graph.vertices();
while (vertices.hasNext())
{
Vertex u = (Vertex) vertices.next();
Iterator vIterator = graph.adjacentVaxticea(u);
while “Iterator .hasNext (J)
{
Vertex v = (Vertex) vItorator.next(); Iterator wItarator = graph.adjacant‘lerticos(u);
while (uItarator . hastxt O) {
Vertex w = (Vertex) wItarator.next0;
if (v != w)
{
found = found H grapherohdjaoenﬂv, w);
i
}
J.
}
return found; } The graph can be implemented either by an edge fist, an adjacency list or an adjacency
matrix. Which choice for the graph implementation gives rise to the most eﬁcient algorithm
{the algorithm with the best woret case running time)? Explain why this is the best choice. graph implementation: if the graph is dense then adjacency matrix, if the graph is sparse
(only a few edges) then adjacency list Explanation: Let us compare the worst. case running times of vertices(), adjacentVertices(v)
and areAdiacenﬂv. w} for the three different implementations of a graph. Page 9 of9 adjacency adjacency edge list. list matrix
0(a) 0(a) 0(a)
0(m) 0(des(v)) 0(n)
0(m) 0(min(des(v), deem» 0(1) operation
verticeso
adjacentVertices(v)
arehdjacenﬁv, w) Since verticasO has the same worst case running time for the three different implemen—
tations, we only have to compare adj acentVertices and aretdj acent. Since deg(v) g m
for all u, it is immediate clear that the adjacency list gives rise to aa as least as efﬁcient
algorithm as the edge list. If we choose the adjacency list, then the combined cost of the calls of adj acentVertices
and areAdjacent is Z deg(u) + E Zdeghr) + Z z Z Inin(deg(v), deg(w) uEV «EV Irvvi: uEV uwu tow
= m + 2 deem)? + Z Z Z min(deg(v).deg(w))
uEV uEVﬂwu w~u where we use 1) ~ 1:; to denote that v and u are adjacent. For the adjacency matrix we obtain ZMZZMZZ‘ZI ueV uEVu—m uev u~u w~u n2+mn+z Z :1. uEV ow ww I! If the graph is dense (there are 9012) edges). each vertex has degree 9(n) Hence, the
adjacency matrix gives rise to a more efﬁcient algorithm. if the graph is (very) sparse, then the adjacency list gives rise to a more efﬁcient algorithm. ...
View
Full Document
 Winter '09
 MixProfs

Click to edit the document details