Prelim 2 Solution. CS 2110, 24 April 2018, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph.

Similar documents
Prelim 2. CS 2110, 24 April 2018, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph.

Prelim 2 Solution. CS 2110, 24 April 2018, 5:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

Prelim 2. CS 2110, 24 April 2018, 5:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

Prelim 2. CS 2110, 16 November 2017, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

Prelim 2 SOLUTION. CS 2110, 16 November 2017, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

Prelim 2, CS :30 PM, 25 April Total Question Name Short Search/ Collections Trees Graphs

Prelim 2. 5:30 PM, 25 April Total Question Name Short Search/ Collections Trees Graphs. Max Score Grader

Prelim 2 Solution. CS 2110, November 19, 2015, 5:30 PM Total. Sorting Invariants Max Score Grader

Prelim 2. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

Prelim 2. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

Prelim 2 Solution. CS 2110, November 19, 2015, 7:30 PM Total. Sorting Invariants Max Score Grader

Total Score /1 /20 /41 /15 /23 Grader

Prelim 2 Solutions. CS 2110, November 20, 2014, 7:30 PM Extra Total Question True/False Short Answer

Prelim 2. CS 2110, April 26, 2016, 5:30 PM Total Question True/False Complexity Heaps Trees Graphs Max Score Grader

Prelim 2. CS 2110, 5:30 PM, November 17, 2016

Prelim 2 Solution. CS 2110, April 26, 2016, 5:30 PM

Prelim 2 Solution. CS 2110, April 26, 2016, 7:30 PM

Prelim 2, CS2110. SOLUTION

Prelim 2 SOLUTION. 5:30 PM, 25 April Total Question Name Short Search/ Collections Trees Graphs

Final exam. CS 2110, December 15, 2016, 9:00AM

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

Prelim 1. CS 2110, 13 March 2018, 5:30 PM Total Question Name Short answer

Prelim 1. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

Prelim 1, Solution. CS 2110, 13 March 2018, 7:30 PM Total Question Name Short answer

Prelim 1. CS2110, October 2, 2014, 5:30 PM Extra Total Question TrueFalse Multiple Object Oriented

Final Exam. CS2110 Spring May 12, Total. Max Score

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Prelim 1. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer. OO Recursion Loop invariants Max Score Grader

ext Total Score /20 /20 /15 /20 /25 /5 Grader

Total Score /15 /20 /30 /10 /5 /20 Grader

Prelim 1. CS 2110, 14 March 2017, 5:30 PM Total Question Name Short answer. OO Recursion Loop invariants Max Score Grader

Prelim 1. CS 2110, March 15, 2016, 5:30 PM Total Question Name True False. Short Answer

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

Recitation 9. Prelim Review

Prelim 1. CS 2110, March 15, 2016, 7:30 PM Total Question Name True False. Short Answer

Total Score /15 /20 /30 /10 /5 /20 Grader

XC Total Max Score Grader

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Data Structures Brett Bernstein

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

"Organizing is what you do before you do something, so that when you do it, it is not all mixed up." ~ A. A. Milne SORTING

SORTING. Insertion sort Selection sort Quicksort Mergesort And their asymptotic time complexity

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

CS/ENGRD2110: Final Exam

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

CS210 (161) with Dr. Basit Qureshi Final Exam Weight 40%

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

Points off Total off Net Score. CS 314 Final Exam Spring 2016

CS 314 Final Fall 2012

CS211 Spring 2005 Prelim 2 April 19, Instructions

CSE100 Practice Final Exam Section C Fall 2015: Dec 10 th, Problem Topic Points Possible Points Earned Grader

CS 251, LE 2 Fall MIDTERM 2 Tuesday, November 1, 2016 Version 00 - KEY

Course Review for Finals. Cpt S 223 Fall 2008

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Computer Science E-22 Practice Final Exam

& ( D. " mnp ' ( ) n 3. n 2. ( ) C. " n

Undirected Graphs. DSA - lecture 6 - T.U.Cluj-Napoca - M. Joldos 1

SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY

CSE332 Summer 2012 Final Exam, August 15, 2012

HEAPS & PRIORITY QUEUES

Instructions. Definitions. Name: CMSC 341 Fall Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII.

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring Instructions:

CMSC132, Practice Questions

Graphs - II. Announcements. Where did I leave that book? Where did I leave that book? Where did I leave that book? CS 2110, Fall 2016

Name Section Number. CS210 Exam #3 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

GRAPHS Lecture 17 CS2110 Spring 2014

Final Examination CSE 100 UCSD (Practice)

Announcements HEAPS & PRIORITY QUEUES. Abstract vs concrete data structures. Concrete data structures. Abstract data structures

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Largest Online Community of VU Students

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

COMP103 Test. 5 Sept, 2007

n 2 ( ) ( ) + n is in Θ n logn

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

University of Illinois at Urbana-Champaign Department of Computer Science. Final Examination

CS 2604 Data Structures Midterm Summer 2000 U T. Do not start the test until instructed to do so!

CS521 \ Notes for the Final Exam

Cornell University Computer Science 211 Second Preliminary Examination 18 April 2006

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

Homework Assignment #3 Graph

Spanning Trees 4/19/17. Prelim 2, assignments. Undirected trees

Spanning Trees. Lecture 22 CS2110 Spring 2017

( ). Which of ( ) ( ) " #& ( ) " # g( n) ( ) " # f ( n) Test 1

CS200 Final Exam Fall 2007

CS 61B Summer 2005 (Porter) Midterm 2 July 21, SOLUTIONS. Do not open until told to begin

( ) ( ) C. " 1 n. ( ) $ f n. ( ) B. " log( n! ) ( ) and that you already know ( ) ( ) " % g( n) ( ) " #&

Graph Algorithms. Chapter 22. CPTR 430 Algorithms Graph Algorithms 1

Final Exam. COMP Summer I June 26, points

CS61BL. Lecture 5: Graphs Sorting

PRIORITY QUEUES AND HEAPS

CS171 Final Practice Exam

EXAMINATIONS 2016 TRIMESTER 2

ASYMPTOTIC COMPLEXITY

CS 170 Second Midterm ANSWERS 7 April NAME (1 pt): SID (1 pt): TA (1 pt): Name of Neighbor to your left (1 pt):

CS4800: Algorithms & Data Jonathan Ullman

Jana Kosecka. Red-Black Trees Graph Algorithms. Many slides here are based on E. Demaine, D. Luebke slides

Transcription:

Prelim 2 Solution CS 2110, 24 April 2018, 7:30 PM 1 2 3 4 5 6 7 Total Question Name Short Heaps Tree Collections Sorting Graph answer Max 1 16 10 20 11 18 24 100 Score Grader The exam is closed book and closed notes. Do not begin until instructed. You have 90 minutes. Good luck! Write your name and Cornell NetID, legibly, at the top of every page! There are 6 questions on 8 numbe pages, front and back. Check that you have all the pages. When you hand in your exam, make sure your pages are still stapled together. If not, please use our stapler to reattach all your pages! We have scrap paper available. If you do a lot of crossing out and rewriting, you might want to write code on scrap paper first and then copy it to the exam so that we can make sense of what you handed in. Write your answers in the space provided. Ambiguous answers will be conside incorrect. You should be able to fit your answers easily into the space provided. In some places, we have abbreviated or condensed code to uce the number of pages that must be printed for the exam. In others, code has been obfuscated to make the problem more difficult. This does not mean that it s good style. Academic Integrity Statement: I pledge that I have neither given nor received any unauthorized aid on this exam. I will not talk about the exam with anyone in this course who has not yet taken Prelim 2. (signature) 1. Name (1 point) Write your name and NetID, legibly, at the top of every page of this exam. 1 of 8

2. Short Answer (16 points) (a) True / False (8 points) Circle T or F in the table below. (a) T F All search algorithms take O(n 2 ) time in the worst case. False. It s easy to write one that takes more. (b) T F If a class implements Iterator, it must also implement Iterable. False. Iterator is typically implemented by a private inner class, not the same class. (c) T F It is best to store sparse graphs in an adjacency matrix and dense graphs in an adjacency list. False. Storing a sparse graph in an adjacency matrix wastes space and makes processing the neighbors of a node take more time. (d) T F ArrayList<Node> is not a subtype of ArrayList<Object> even if Node extends Object. True. See a line in the entry for generics in JavaHyperText. (e) T F An algorithm s time complexity can be both O(n 3 ) and O(n 2 ). True. Any algorithm that is O(n 2 ) is also O(n 3 ). (f) T F ArrayList<double> mylist= new ArrayList<>(); is valid Java. False. Type parameters cannot be primitive types. (g) T F Consider an undirected graph with set of edges E and set of vertices V. It is a tree iff E = V 1. False. There must also be no cycles. (h) T F Any planar graph can be topologically sorted. False. The graph must be acyclic. (b) GUI (3 points) What three steps are requi to listen to an event in a Java GUI? 1. Have some class C implement an interface IN that is connected with the event. 2. In class C, override methods requi by interface IN; these methods are generally called when the event happens. 3. Register an object of class C as a listener for the event. That object s methods will be called when event happens. (c) Red-Black Trees (5 points) What is the full -black tree invariant? 1. The tree is a binary tree. 2. Every node is either or black. 3. The root is black. 4. If a node is, then its (non-null) children are black. 5. For each node, every path to a descendant null node contains the same number of black nodes. 2 of 8

3. Heaps (10 Points) (a) 6 points State whether each tree below is a valid max-heap, in which the priorities are the values. If it is not, state which invariant is unsatisfied. No partial cit given. 15 13 11 12 8 10 valid max-heap 14 7 1 22 17 15 invalid: completeness invariant unsatisfied 12 11 14 19 15 9 8 invalid: heap invariant unsatisfied (b) 4 points The int array b below corresponds to a min-heap of integers in which the values are the priorities. Suppose the heap has size 7 and b[0..6] contains these 7 integers. b = [3 8 4 9 11 5 10] Draw the state of b after calling b.poll(). Give your solution as an array. (Points deducted if you did not write your solution as an array.) [4 8 5 9 11 10] 4 8 5 9 11 10 4. Trees (20 Points) (a) 2 points What is the worst case time complexity for determining if a value is contained in: a Red Black Tree with n nodes? O(log n) a Binary Search Tree with n nodes? O(n) (b) 4 points Write down the order in which this tree s nodes are printed in preorder, inorder, and postorder traversals. Preorder: A Y M B W J I Inorder: M B Y A J W I Postorder: B M Y J I W A Y A W M J I B 3 of 8

(c) 4 points Draw the binary search tree that results from inserting the following nodes, one by one, into an initially empty tree: 7, 4, 5, 1, 9, 8. Two pts. off for a mistake; 0 if your answer does not resemble the correct tree. 7 / \ 4 9 / \ / 1 5 8 (d) 10 points Class Ppl (for People), to the right, represents a person and their kids. In the tree to the right, Anne is the first generation. Her kids are Bob, Con, and Dan; they are Anne s generation 2. Bob has 1 kid, Eve, and Dan has 2 kids, Frank and Grace. Eve, Frank, and Grace are Anne s generation 3. Etcetera. Complete method maxgen below. public class Ppl { private String name; private Set<Ppl> kids;... Anne / \ Bob Con Dan \ Eve Frank Grace /** Return the maximum number of generations that this Ppl can trace * forward through their kids. * * For example, in the tree to the right above, * Anne.maxGen() = 3 // Tree contains some of Anne's kid's kids * Bob.maxGen() = 2 // Bob's Tree contains Bob's kid * Con.maxGen() = 1 // Con's tree contains only Con * Frank.maxGen() = 1 // Frank's tree contains only Frank */ public int maxgen() { int mgen= 1; for (Ppl s : kids) { mgen= Math.max(mGen, 1 + s.maxgen()); return mgen; 4 of 8

5. Collections and Interface (11 Points) Class Multiset E, decla below, implements a multiset like a set but elements can be in it more than once. Implement methods contains, add, and remove. Assume all other methods requi by Collection have already been implemented. Note: interpreting size as the number of entries in the map instead of the number elements in the multiset is a mistake. Suppose I gave you a bag containing ten dimes. Would you say its size is 1 or 10? /** An instance is a multiset --an unorde collection in which there can be * multiple instances of the same element. */ public class Multiset<E> implements Collection<E> { private int size; // Number of elements in this multiset private Map<E, Integer> elemnum; // Mapping of element in this multiset to // its number of occurrences (which is > 0) /** Constructor: An empty multiset. */ public Multiset() { elemnum= new TreeMap<E, Integer>(); /** Return whether this multiset contains ob. */ (1 point) public boolean contains(object ob) { elemnum.get(ob)!= null; /** Add e to multiset. Return whether elemnum was modified in any way. */ (4 points) public boolean add(e e) { if (contains(e)) {. OR Integer s= elemnum.get(e); elemnum.put(e, map.get(e)+1); if (s == null) elemnum.put(e, 1); else { else elemnum.put(e, s+1); elemnum.put(e, 1); size++;. return true; size++; return true; /** Remove ob from multiset if present. Return whether it was removed.*/ (6 points) public boolean remove(object ob) { Integer s= elemnum.get(ob); if (s == null) return false; if (s == 1) elemnum.remove(ob); else elemnum.put((e)ob, s-1); size--; return true; 5 of 8

6. Sorting (18 Points) (a) 4 points. Consider the following class Author. Order the list of Author in decreasing order of bookswritten. If two authors have written the same number of books, order by decreasing number of copies sold. Complete method compareto(...); it must implement the standard compareto specification. /** An instance represents a comparable author object*/ public class Author implements Comparable<Author> { private String name; private int bookswritten; private int copiessold;// total number of copies of all the books sold.... /** Compare this object with ob for order. */ @Override public int compareto(author ob) { // there are other solutions if (ob.bookswritten == bookswritten) return ob.copiessold - copiessold; return ob.bookswritten - bookswritten; (b) 6 points. Using method compareto(), complete method selectionsort(), below. That is, complete the comment that begins the body of the for-loop as a high-level statement saying what is done to ensure that the loop invariant remains true. (2 points) Then implement the high-level statement. (4 points) We deducted points for an inner loop that swapped b[k] and b[j] many times instead of performing one swap after the index of the min value is found. No regrade request on this will get points back. public void selectionsort(author[] b) { // inv: b[0..i-1] is sorted and b[0..i-1] <= b[i..] (using compareto) for (int i= 0; i < b.length; i= i+1) { // Swap b[i] with the minimum of b[i..] int k= i; // inv: b[k] is min of b[i..j-1] for (int j= i+1; j < b.length; j= j+1) { if (b[k].compareto(b[j]) < 0) k= j; // Swap b[i] and b[k] int t= b[i]; b[i]= b[k]; b[k]= t; (c) 2 points. O(n 2 ), O(n 2 ) What is the worse-case time and expected time of selection sort? (d) 6 points State the tightest expected time complexity of quicksort, mergesort, and insertionsort. For quicksort, assume it is the version that uces the space as much as possible. quicksort: O(n log(n)) mergesort: O(n log(n)) insertionsort: O(n 2 ) 6 of 8

7. Graphs (24 Points) A coloring of a graph is an assignment of colors to the nodes of a graph. An edge is properly colo if the two nodes it connects have different colors. A proper coloring is a coloring in which all edges are properly colo. (a) 3 points Which of the following are proper colorings? blue blue blue gray gray gray yes no blue yes (c) 4 points The chromatic number of a graph G, written as (χ G ), is the minimum number of colors needed to properly color the graph. For each of the graphs below, write down χ G and properly color the graph using χ colors. To assign a color to a node, write the name of the color next to the node, as in part (a). χ G = 3 χ G = 3 (d) 4 points Draw a graph whose chromatic number is 2 (there exists a proper coloring using only two colors). Use at least 4 nodes. The graph must be a bipartite graph with at least four nodes. For example: 7 of 8

Complete method isproper, below. The graph is undirected and connected. Starting with all nodes unchecked and u some node of the graph, the call isproper(u) will determine whether the graph is properly colo. Use the English phrases n was checked and check n to test whether a node n has already been traversed and to mark it as checked, respectively. Use n.color for the color of node n. Use a loop for each neighbor m of n. The precondition of any call implies that n should be checked only if its edges are properly colo. That is the reason for the first loop over the neighbors. /** Let E be the set of edges that are reachable along unchecked paths from n. * Return true iff all edges in E are properly colo. * Precondition: all edges leaving a checked node are properly colo. * Precondition: n is unchecked. */ static public boolean isproper(node n) { for each neighbor m of n { if (n.color == m.color) return false; check n; for each neighbor m of n { if (m is unchecked &&!isproper(m)) return false; return true; (f) 1 point. Method isproper traverses the graphs in some fashion. It is similar to one of the following. Circle the one to which it is similar. kruskal. prim. shortest path. dfs. bfs. The answer is dfs. (g) 5 points. Two parts of the invariant of the shortest path algorithm are: For f in the frontier set, d[f] is the length of the shortest path to f that consists of nodes except for f. There are no edges from the settled set to the far-off set. State (1) the third part of the invariant and (2) the theorem that is proved about the invariant. (1) For each node u in the settled set, d[u] is the length of the shortest path from the start node to node u. (2) For f in the frontier set with minimum d-value (over nodes in the frontier set), d[f] is indeed the length of the shortest path from the start node to f. 8 of 8