(a) Write code to do this without using any floating-point arithmetic. Efficiency is not a concern here.

Similar documents
CS521 \ Notes for the Final Exam

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

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

ECE250: Algorithms and Data Structures Final Review Course

CS 146 Midterm Exam 2 Grade: Professors Howard, Fine, and Howard have proposed the following sorting algorithm:

( ) + n. ( ) = n "1) + n. ( ) = T n 2. ( ) = 2T n 2. ( ) = T( n 2 ) +1

( ) n 3. n 2 ( ) D. Ο

Review of course COMP-251B winter 2010

logn D. Θ C. Θ n 2 ( ) ( ) f n B. nlogn Ο n2 n 2 D. Ο & % ( C. Θ # ( D. Θ n ( ) Ω f ( n)

COMP 251 Winter 2017 Online quizzes with answers

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

( D. Θ n. ( ) f n ( ) D. Ο%

DESIGN AND ANALYSIS OF ALGORITHMS

Department of Computer Applications. MCA 312: Design and Analysis of Algorithms. [Part I : Medium Answer Type Questions] UNIT I

9. The expected time for insertion sort for n keys is in which set? (All n! input permutations are equally likely.)

n 2 C. Θ n ( ) Ο f ( n) B. n 2 Ω( n logn)

Your favorite blog : (popularly known as VIJAY JOTANI S BLOG..now in facebook.join ON FB VIJAY

Course Review for Finals. Cpt S 223 Fall 2008

) $ f ( n) " %( g( n)

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

Multiple Choice. Write your answer to the LEFT of each problem. 3 points each

Test 1 Last 4 Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. 2 points each t 1

CSE 332 Autumn 2016 Final Exam (closed book, closed notes, no calculators)

n 2 ( ) ( ) Ο f ( n) ( ) Ω B. n logn Ο

( ) 1 B. 1. Suppose f x

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D.

Computer Science 302 Spring 2017 (Practice for) Final Examination, May 10, 2017

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

CS 112 Final May 8, 2008 (Lightly edited for 2012 Practice) Name: BU ID: Instructions

CS171 Final Practice Exam

CSci 231 Final Review

( ) D. Θ ( ) ( ) Ο f ( n) ( ) Ω. C. T n C. Θ. B. n logn Ο

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

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final

1 Format. 2 Topics Covered. 2.1 Minimal Spanning Trees. 2.2 Union Find. 2.3 Greedy. CS 124 Quiz 2 Review 3/25/18

Algorithm Design (8) Graph Algorithms 1/2

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

CS171 Final Practice Exam

Model Answer. Section A Q.1 - (20 1=10) B.Tech. (Fifth Semester) Examination Analysis and Design of Algorithm (IT3105N) (Information Technology)

Final Examination CSE 100 UCSD (Practice)

CS 216 Fall 2007 Final Exam Page 1 of 10 Name: ID:

Introduction to Algorithms Third Edition

CS1800 Discrete Structures Fall 2016 Profs. Aslam, Gold, Ossowski, Pavlu, & Sprague December 16, CS1800 Discrete Structures Final

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

CS302 Data Structures using C++

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

End-Term Examination Second Semester [MCA] MAY-JUNE 2006

CSE 100 Minimum Spanning Trees Prim s and Kruskal

SUGGESTION : read all the questions and their values before you start.

Thomas H. Cormen Charles E. Leiserson Ronald L. Rivest. Introduction to Algorithms

Chapter 9 Graph Algorithms

INDIAN STATISTICAL INSTITUTE

11/22/2016. Chapter 9 Graph Algorithms. Introduction. Definitions. Definitions. Definitions. Definitions

CSE 373 Final Exam 3/14/06 Sample Solution

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

Lecture 6 Basic Graph Algorithms

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

Virtual University of Pakistan

Solutions to Exam Data structures (X and NV)

15CS43: DESIGN AND ANALYSIS OF ALGORITHMS

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

Design and Analysis of Algorithms - - Assessment

Lecture 5: Sorting Part A

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

L.J. Institute of Engineering & Technology Semester: VIII (2016)

END-TERM EXAMINATION

Shortest path problems

2. True or false: even though BFS and DFS have the same space complexity, they do not always have the same worst case asymptotic time complexity.

Review for Midterm Exam

Cs502 Solved MCQS MidTerm

University of New Mexico Department of Computer Science. Final Examination. CS 362 Data Structures and Algorithms Spring, 2006

Dijkstra s Algorithm Last time we saw two methods to solve the all-pairs shortest path problem: Min-plus matrix powering in O(n 3 log n) time and the

CSE 421 Greedy Alg: Union Find/Dijkstra s Alg

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

CISC 320 Midterm Exam

CS 2150 Final Exam, Spring 2018 Page 1 of 10 UVa userid:

Reference Sheet for CO142.2 Discrete Mathematics II

Data Structures Brett Bernstein

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

4/8/11. Single-Source Shortest Path. Shortest Paths. Shortest Paths. Chapter 24

The ADT priority queue Orders its items by a priority value The first item removed is the one having the highest priority value

FACULTY OF SCIENCE ACADEMY OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING ADVANCED DATA STRUCTURES AND ALGORITHMS EXAM EXAMINATION JUNE 2014

CS350: Data Structures Dijkstra s Shortest Path Alg.

Chapter 9. Priority Queue

Sankalchand Patel College of Engineering - Visnagar Department of Computer Engineering and Information Technology. Assignment

Algorithms: Design & Practice

CS200 Final Exam Fall 2007

Total Points: 60. Duration: 1hr

University of the Western Cape Department of Computer Science

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination T09:00

COMP Data Structures

Chapter 9 Graph Algorithms

Computer Science E-22 Practice Final Exam

Algorithms and Data Structures (INF1) Lecture 15/15 Hua Lu

CSE 332 Winter 2015: Final Exam (closed book, closed notes, no calculators)

Course goals. exposure to another language. knowledge of specific data structures. impact of DS design & implementation on program performance

Sorting and Searching

CS 112 Final May 8, 2008 (Lightly edited for 2011 Practice) Name: BU ID: Instructions GOOD LUCK!

CMSC132, Practice Questions

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

Transcription:

CS 146 Final Exam 1 Solutions by Dr. Beeson 1. Analysis of non-recursive algorithms. Consider the problem of counting the number of points with integer coordinates (x,y) on the circle of radius R, where R is a positive integer. (a) Write code to do this without using any floating-point arithmetic. Efficiency is not a concern here. static int CirclePoints(int R) // count the points with integer coordinates on the circle // of radius R > 0 { int x,y,ans=0; for(x= -R;x<=R; x++) for(y= -R;y<=R; y++) if(x*x + y*y == R) ++ans; return ans; } (b) Use Θ notation to estimate the running time of your code in part (a) in terms of R. Two nested for-loops, each running over 2R+1 values: T(n) = Θ(R 2 ) (c) With floating-point arithmetic allowed, write code that will be faster for large R. static int CirclePoints(int R) // count the points with integer coordinates on the circle // of radius R > 0 { int x,y,ans=2; double ysq, epsilon = 1.0e-8; for(x= -R+1;x<R; x++) { ysq = R*R x*x; y = (int) (Math.sqrt(ysq) + epsilon); if(y*y + x*x == R*R) ++ans; } return ans; } (d) Use Θ notation to estimate the running time of your code in part (c) in terms of R: Now there is only one loop, so T(n) = : T(n) = Θ(R). Computing the square root takes a long time compared to integer arithmetic though, so the constant is bigger than just one per line.

2. Indicate, for each pair of expressions (A,B) in the table below, whether A is O, or Θ of B. Write Yes or No in each blank box of the table. [You will only receive points if you answer more than 50% correct, since you can get 50% correct by guessing.] A B O Θ 2 n n 3 No No n n 5 + n Yes No n lg n 5 No No n lg n + n Yes Yes n 5 + n n 5 Yes Yes n 23 ( n 56 ) Yes No n 23 n 28 Yes No n lg n n 2 Yes No n lg n n No No 3. Linked lists. The class StringList has these members: { String key; StringList next; } Write a method void append( StringList x) that appends x to the end of this. For example, if this is ( cat, dog ) and x is ( giraffe, anteater ), then after running append, this has the value ( cat, do, giraffe, anteater ). void append(stringlist x) // append x to the end of this { StringList marker; for(marker=this;marker.next;marker=marker.next) ; // find the end of this marker.next = x; // point the end of this to x }

4. Analyzing recursive code using recurrence relations. A recursive palindrome is a string that it is a palindrome, and in addition both its left half and its right half (if they have more than one character) are recursive palindromes. The left half and right half of a string of odd length 2n + 1 or of even length 2n are the first n characters and the last n characters. For example, WOWWOW and ABACABA are recursive palindromes but MADAM is not. For another example, WOWWOWXWOWWOW is a recursive palindrome. Assume only upper-case letters will be used. We will consider two problems about recursive palindromes: One, testing a string of length n to see if it is or is not a recursive palindrome. The function to do this can be called IsRP. The second problem is counting the number of recursive palindromes of length n. The function to do this can be called CountRP. Assume that it returns an int, i.e. BigInteger is not needed. (a) Write a recurrence relation for the worst-case running time T(n) of IsRP. T(n) = 2 T(n/2) + cn since there are two recursive calls (to check the left and right half) and checking whether x is a palindrome takes cn steps. (b) Solve that recurrence relation to give an estimate for T(n). ( Estimate means that your answer uses big-o notation.) T(n) = n lg n. This is the same recurrence relation as for merge sort. (c) Write a recurrence relation for the worst-case running time T(n) of CountRP. T(n) = T(n/2). The code is very simple, and only one recursive call will be made. ( Even though there are two lines with recursive calls, only one will be executed.) static int CountRP(int n) { int ans; if(n==1 n==2) return 26; if(n % 2 == 0) return CountRP(n/2); return 26* CountRP(n/2); } (b) Solve that recurrence relation to give an estimate for T(n). ( Estimate means that your answer uses big-o notation.) T(n) = lg n

5. Binary Search Trees. The picture represents a binary search tree. The numbers shown are arbitrary node labels, not numbers representing the contents of the nodes. The contents are not shown. If node 1 is deleted, using binary search tree deletion, what will be the new root node? Answer: node 12, the successor of 1. 6. Red-black trees. For each of the following two trees, either indicate how to color the nodes red and black (use R and B to label the nodes) to make the tree a red-black tree, or explain why that is not possible. Answer: the second tree cannot be a red-black tree because it has a branch of length 7, more than twice that of its shortest branch (three). The first tree can be made a red-black tree by coloring 2,6, and 7 red, and the other nodes black.

7. B-tree insertion. A new key 4 is to be inserted into the following B-tree. This B-tree 2,3, or 4 children per internal node. Draw a similar diagram showing the B-tree after the insertion of 4. Use the one-pass insertion algorithm, i.e. the one given in your textbook 8. Merge sort. The following array is to be sorted: 4 6 8 1 10 5 15 13 2 16 14 7 3 9 11 12 (a) If mergesort is called to sort this array, how many recursive calls will there be (not counting the top-level call)? 30 (Remark: the textbook s mergesort does get called on arrays of length 1). There will be calls to sort 2 subarrays of length 8, 4 of length 4, 8 of length 2, and 16 of length 1, making a total of 30. (b) What will be the maximum recursion depth, i.e., the maximum number of nested calls that have not been returned from yet? 5 (Here we DO count the top-level call.) (c) What will the array look like immediately after the return from the first recursive call?

Then the first half will be sorted and the second half unchanged. 1 4 5 6 8 10 13 15 2 16 14 7 3 9 11 12 9. Quick sort. The following array is to be sorted (it s the same as the one above): 4 6 8 1 10 5 15 13 2 16 14 7 3 9 11 12 (a) if quicksort is used to sort this array, what will the array look like just before the first recursive call? Pivoting will have been done. The result is 4 6 8 1 10 5 2 7 3 9 11 12 15 16 14 13 (b) What will the array look like just after the return from the first recursive call? The part before 12 will be sorted 1 2 3 4 5 6 7 8 9 10 11 12 15 16 14 13 10. Heap algorithms. The following array represents a binary tree. 4 1 7 9 5 6 3 8 2 10 11 (a) Using the convention we used for heaps, draw a picture of this tree. (b) After calling BUILD-MIN-HEAP, the resulting array will be a min-heap. Show it in array form: 1 2 3 4 5 6 7 8 9 10 11

11. Execute Prim s algorithm to find a minimal spanning tree in the following graph, starting from vertex 2. List the vertices in the order they come off the queue, and then highlight the minimal spanning tree by drawing it right on the diagram. Vertices in the order they come off the queue: 2,7,3,4,1,9,6,5,8,10. Edges of the tree are 7,9,3,4,1,6,2,14,17. Sorry, I don t have a way to draw those edges heavier, so this will have to do. Total weight 63.

12. Execute Kruskal s algorithm to find a minimal spanning tree in the following graph (which is, incidentally, the same graph as in the previous problem). List the edges in the order they are added to the answer, and also highlight the minimal spanning tree by drawing it right on the diagram. Since the edges have unique weights, you can identify an edge by its weight, e.g. you can write 11 instead of (4,5). Edges: 1,2,3,4,6,7,9,14,17. Total weight 63. Check: that s the same total weight and the same MST as we got from Prim s algorithm. It has to be not only the same weight but the same tree because the edge weights are unique.

13. If we run Dijkstra s algorithm on the graph shown below (which is the same as the graph in the previous problem, but here is another picture of it), starting from node 2, (a) how many nodes will be removed from the queue before every node gets its correct distance from node 2 calculated? Answer [just one number] : 6 (b) List the nodes in the order of their removal from the queue. Answer [a list of numbers]: 2,7,3,4,1,9,6,5,8,10. When 9 comes off, and its neighbors are marked, then those numbers don t change after that, so 6 is the answer to (a). The diagram is provided for you to use if you wish, but it s not needed to communicate the answer.

14. Needleman-Wunsch. (a) What are the asymptotic time and space requirements of the Needleman-Wunsch algorithm? Express your answers in terms of the maximum length n of the two input strings, using big-o notation. Time: O(n 2 ) Space: O(n 2 ) (b) Execute the Needleman-Wunsch algorithm to find the best alignment of COPE and CAP, scoring exact matches as 1 and non-matches as 0, with a gap penalty of 1 (i.e. matching a letter with a gap scores -1). Use the following table to execute the algorithm, showing the predecessor arrows as was done in class. Here I use D, U, L to indicate diagonal, up, left, as I don t have a way to make arrows. C O P E 0-1 -2-3 -4 C -1 1D 0L -1L -2L A -2 0U 1D 0D -1D P -3-1U 0D 2D 1L The best alignment is COPE CAP- and the score of that alignment is 1

15. Basic properties of some algorithms we studied (a) What two algorithms we studied used a priority queue? Dijstra and Prim (b) Which algorithm has a recursive version, depth-first search or breadth-first search? Depth-first search (c) Which search algorithm uses a stack? Depth-first search (d) Which algorithm is used for finding, in one run, the shortest distance between all possible pairs of points in a weighted directed graph? Floyd-Warshall (e) Which algorithm can detect negative cycles in a graph? Bellman-Ford 16. Basic properties of some data structures (a) What kind of tree that we studied has this property? any two leaf nodes have same depth. B-tree (b) True or false: If A and B are the left and right children of some node of a heap, then we must have A B. False (c) What kind of tree is used in the implementation of databases? B-trees (d) True or false: in a binary search tree, the height of the tree is logarithmic in the number of nodes. False (e) What is the worst-case running time for the insertion algorithm for binary search trees? O(n). I accepted O(height) also. (f) What is the worst-case running time for the insertion algorithm for red-black trees? O(lg n). I accepted O(height) here too.

17. Graphs and their representations. How would you represent the air transport network of the world by a weighted graph? (a) The nodes would be airports. (b) The edges would be pairs of cities connected by direct flights. It would be a directed graph. (c) The weights would be perhaps the cost per person, or cost per pound, or cost per flight, or for some purposes even hours it takes to fly that route. (d) How could this graph, plus some additional information, be used to run a ticketselling website where you would enter your starting and destination cities, and travel dates, and get the best flights? What algorithms would be used? Dijkstra s algorithm could be used to find the cheapest or shortest path. However, this leaves the element of time out of it. Finding flights that don t leave you stranded in Chicago for two days requires the additional information about when the flights are scheduled. Then, for example, your graph s nodes would be pairs (airport, time), and there would be waiting edges between (x,t) and (x, t2) whenever t < t2. A weight could be assigned to those edges representing the cost of waiting. You don t need all the infinitely many possible times, just the pairs (x,t) when a flight leaves or arrives from x. That still makes a big graph, but not too big for Dijkstra s algorithm. Now you can use Dijkstra directly to do what Hotwire, etc. do.