ACM today Some nice unix commands… practice problems? code.google.com/codejam/ This week: beyond Floyd-Warshall.

Slides:



Advertisements
Similar presentations
Jotto! JRsSRsElderly slate 3 This term's first class to guess another's word earns 1 problem... slate 2slate 1 This term's last class to have its word.
Advertisements

Graph Theory Arnold Mesa. Basic Concepts n A graph G = (V,E) is defined by a set of vertices and edges v3 v1 v2Vertex (v1) Edge (e1) A Graph with 3 vertices.
§3 Shortest Path Algorithms Given a digraph G = ( V, E ), and a cost function c( e ) for e  E( G ). The length of a path P from source to destination.
CSE 390B: Graph Algorithms Based on CSE 373 slides by Jessica Miller, Ruth Anderson 1.
Greed is good. (Some of the time)
Jotto! JRsSRsElderly A word-guessing game similar to mastermind… slate 3 This term's first class to guess another's word earns 1 problem... slate 2slate.
1 Maximum flow sender receiver Capacity constraint Lecture 6: Jan 25.
ACM so far… Sep 11 Welcome! and DP problems ~ 6 problems Sep 18 Lab session ~ 6 problems Sep 25 Discussion session on graph problems ~ 6 problems Oct 2.
1 Review of some graph algorithms Graph G(V,E) (Chapter 22) –Directed, undirected –Representation Adjacency-list, adjacency-matrix Breadth-first search.
CS 206 Introduction to Computer Science II 11 / 07 / 2008 Instructor: Michael Eckmann.
Graphs Graphs are the most general data structures we will study in this course. A graph is a more general version of connected nodes than the tree. Both.
Semester 10 Time sure flies.. PotW Solution One possible solution is to randomly search the grid: o At each point in your search, look at the (up to four)
Jotto! SophsJrsSrs audio 1audio 2audio 1 Frosh audio 2 graze 3graze 1 graze 2 alloy 1 alloy 2 fresh 2fresh 1fresh 2fresh 1 This term's first class to guess.
Introduction To Algorithms CS 445 Discussion Session 8 Instructor: Dr Alon Efrat TA : Pooja Vaswani 04/04/2005.
1 Maximum Flow w s v u t z 3/33/3 1/91/9 1/11/1 3/33/3 4/74/7 4/64/6 3/53/5 1/11/1 3/53/5 2/22/2 
Lectures on Network Flows
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
CPSC 411, Fall 2008: Set 4 1 CPSC 411 Design and Analysis of Algorithms Set 4: Greedy Algorithms Prof. Jennifer Welch Fall 2008.
CS 206 Introduction to Computer Science II 11 / 10 / 2008 Instructor: Michael Eckmann.
More Graph Algorithms Weiss ch Exercise: MST idea from yesterday Alternative minimum spanning tree algorithm idea Idea: Look at smallest edge not.
CPSC 411, Fall 2008: Set 4 1 CPSC 411 Design and Analysis of Algorithms Set 4: Greedy Algorithms Prof. Jennifer Welch Fall 2008.
Please open your laptops, log in to the MyMathLab course web site, and open Daily Quiz 18. You will have 10 minutes for today’s quiz. The second problem.
Minimum Spanning Trees What is a MST (Minimum Spanning Tree) and how to find it with Prim’s algorithm and Kruskal’s algorithm.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Advanced Algorithms Piyush Kumar (Lecture 5: Weighted Matching) Welcome to COT5405 Based on Kevin Wayne’s slides.
CS223 Algorithms D-Term 2013 Instructor: Mohamed Eltabakh WPI, CS Introduction Slide 1.
Minimal Spanning Trees What is a minimal spanning tree (MST) and how to find one.
1 GRAPHS - ADVANCED APPLICATIONS Minimim Spanning Trees Shortest Path Transitive Closure.
CS 146: Data Structures and Algorithms July 21 Class Meeting
SPANNING TREES Lecture 21 CS2110 – Spring
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Representing and Using Graphs
Minimum Spanning Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
MST and Max Flow CS3233. Overview Two Graph Problems Minimum Spanning Tree Maximum Flow/Minimum Cut Problem One Data Structure Disjoint Sets.
Dijkstra’s Algorithm. Announcements Assignment #2 Due Tonight Exams Graded Assignment #3 Posted.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Prims’ spanning tree algorithm Given: connected graph (V, E) (sets of vertices and edges) V1= {an arbitrary node of V}; E1= {}; //inv: (V1, E1) is a tree,
Announcements Network Flow today, depending on how far we get, we will do String Matching on Wednesday Then Review for Final next Monday This week’s lab.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports Lecture clinic liaison phone call coding chunky strings.
Curricularizing the ACM... ? Zach Dodds ~ November 13, 2010.
ACM today This week's problems… New and improved :-) ACM table slacking! not slacking… missing entries? let me know…
Recursive Back Tracking & Dynamic Programming Lecture 7.
ACM reminders October HMC Mock contest 9: :30 November regional contest This is the next ACM meeting !! Contest-like problems dynamic.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Graphs A ‘Graph’ is a diagram that shows how things are connected together. It makes no attempt to draw actual paths or routes and scale is generally inconsequential.
CS223 Advanced Data Structures and Algorithms 1 Maximum Flow Neil Tang 3/30/2010.
1 Prim’s algorithm. 2 Minimum Spanning Tree Given a weighted undirected graph G, find a tree T that spans all the vertices of G and minimizes the sum.
Problem Reduction So far we have considered search strategies for OR graph. In OR graph, several arcs indicate a variety of ways in which the original.
SPANNING TREES Lecture 20 CS2110 – Fall Spanning Trees  Definitions  Minimum spanning trees  3 greedy algorithms (incl. Kruskal’s & Prim’s)
SPANNING TREES Lecture 21 CS2110 – Fall Nate Foster is out of town. NO 3-4pm office hours today!
Announcements Finish up Network Flow today Then Review for Final on Monday ◦ HW#5 is due on Monday, let me or the TA’s know if you have trouble starting.
Contest Algorithms January 2016 Describe shortest path trees, SSSP, APSP, and three algorithms: Dijkstra, Bellman-Ford, Floyd-Warshall 9. Shortest Paths.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Harbin, China 2010 finals ACM today… ! (2009) Knapsack DP for NP! Floyd-Warshall DP for APSP! Max Flow.
Contest Algorithms January 2016 Describe the maxflow problem, explain the Ford-Fulkerson, Edmonds-Karp algorithms. Look at the mincut problem, bipartite.
ACM today The Fall competition is getting organized… it's going to be lonely…
TU/e Algorithms (2IL15) – Lecture 8 1 MAXIMUM FLOW (part II)
ACM so far… Sep 6 Welcome! and DP problems ~ 5 problems
I206: Lecture 15: Graphs Marti Hearst Spring 2012.
Jotto! Frosh Sophs Jrs Srs audio 2 audio 1 audio 2 audio 1 graze 2
Graphs.
Outline This topic covers Prim’s algorithm:
Jotto! Sophs Jrs Srs Profs pluot 1 pluot 2 pluot 1 pluot 2 squid 2
ACM today… ! DP for NP! DP for APSP! Knapsack Floyd-Warshall
Algorithms (2IL15) – Lecture 7
CSE 373: Data Structures and Algorithms
Graphs.
CMSC201 Computer Science I for Majors Lecture 12 – Program Design
Presentation transcript:

ACM today Some nice unix commands… practice problems? code.google.com/codejam/ This week: beyond Floyd-Warshall

top screen nice Make sure long-running programs are nice ! top watches the progress of all of knuth's processes. What are are all of these columns saying? Creates a terminal session independent of a particular connection screen particularly this one… nice! screen screen -r to start to resume nice java args +19

Upcoming schedule… Sep 29 Discussion session on new problems: 4 problems Oct 6 Lab session: 4 problems Oct 13 Discussion session on new problems: 4 problems Oct 20 Lab / mock ACM contest, 9pm – 1:00am, 6 problems Oct 27 No class… ACM's fall break… Nov 3 Meeting with HMC teams going to contest Nov 7 Riverside Nov 17 Discussion and wrap-up for the semester You may submit problems until the end of exams…

This week's problems… Read over these problems: Rank in terms of difficulty… and approach.

Current Jotto standings… SophsJrsSrsOthers icily 0 icily 1 strep 2 strep 1 spork 1spork 3spork 0 spend 2 spend ? spend 2 peeps 2peeps 1peeps ?peeps 1 furls 1 furls ?furls 1 I'd call this a "senior moment"

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree.

MST Minimum spanning tree: (Prim’s algorithm) Start anywhere and repeatedly choose the next- smallest edge out from your current tree. Done!

The other three problems… can all be solved with Max Flow

Max Flow A B E D C 13 F source capacity sink The problem how much traffic can get from the source to the sink ? Ford-Fulkerson algorithm Some animations:

Max Flow The problem how much traffic can get from the source to the sink ? A B E D C 13 A B C D E FROM ABCDE F F F TO “Capacity Graph” source sink capacity C

Find a path in C via BFS The problem how much traffic can get from the source to the sink ? A B E D C 13 FROM F TO source sink capacity C A B C D E ABCDE F F need to add this into here…

Create F Create a FLOW GRAPH with the minimum weight from that path A B E D C 13 A B C D E FROM ABCDE F F F TO “Flow Graph” source sink capacity F 12 flow in one direction is negative flow in the other direction

R = C - F Create a RESIDUAL GRAPH with the rest of the capacity after that flow A B E D C 13 A B C D E FROM ABCDE F F F TO “Residual Graph” source sink capacity R 12 reverse edges allow the "undoing" of previous flow!

Keep going! Continue running this on the residual capacity until BFS fails… A B E D C 12/13 F 11/16 0/101/4 0/9 12/12 11/14 7/7 19/20 4/4 source sink There is no longer a path from A to F ! max flow: 23

The max flow algorithm A B E D C 13 F “Residual Graph” source sink capacity flow Don't need to keep R around explicity: Keep only the current flow (F) and the original capacity (C). A B C D E F residual Floyd-Fulkerson 1. Set F to all 0 2. Compute R = C - F 3. BFS in R from source to sink. 3a. If no path, you’re done. 3b. If  a path, add the available capacity to F; goto (2).

Get into the flow! def max_flow(C, source, sink): n = len(C) # C is the capacity matrix F = [[0] * n for i in range(n)] # F is the flow matrix # residual capacity from u to v is C[u][v] - F[u][v] while True: path = BFS(C, F, source, sink) if not path: break # no path - we're done! flow = 9042 # a big number ~ inf. for u,v in path: # find bottleneck flow = min(flow, C[u][v] - F[u][v]) print "Augmenting by", flow for u,v in path: # traverse path to update flow F[u][v] += flow # forward edge up F[v][u] -= flow # backward edge down return sum([F[source][i] for i in range(n)]) A little bit of name contention… edmonds_karp This is the algorithm.

Useful alone, too def BFS(C, F, source, sink): queue = [source] # the BFS queue paths = {source: []} # dictionary of partial paths while queue: u = queue.pop(0) # next node to explore (expand) for v in range(len(C)): # for each possible next node # path from u to v? and not yet at v? if C[u][v] - F[u][v] > 0 and v not in paths: paths[v] = paths[u] + [(u,v)] if v == sink: return paths[v] queue.append(v) # go from v in the future return None A brief BFS algorithm using the Capacity matrix

Setting up… if __name__ == "__main__": # make a capacity graph # node A B C D E F C = [ [ 00, 16, 13, 00, 00, 00 ], # A [ 00, 00, 10, 12, 00, 00 ], # B [ 00, 04, 00, 00, 14, 00 ], # C [ 00, 00, 9, 00, 00, 20 ], # D [ 00, 00, 00, 7, 00, 4 ], # E [ 00, 00, 00, 00, 00, 00 ] ] # F print "C is", C source = 0 # A sink = 5 # F max_flow_value = max_flow( C, source, sink ) print "max_flow_value is", max_flow_value And the code needed to run it… Linked at the ACM website by the slides…

Max Flow Given that nodes are searched alphabetically, what flow amounts will be added next ? Some animations: A B E D C 13 F source capacity 12

The challenge: setting up the MaxFlow graph

dinner number of teams Input Output number of tables # of people in each team can an assignment be made without putting teammates together? 0101 capacity of each table again… end… tables with capacities teams with sizes seating assignments! no teammates

patrol number of fields Input Output number of paths there is a path from field 1 to field 2 smallest # of fields that need to be patrolled so that a round trip is NOT possible (without detection) start (farm) goal (ice cream) Bessie must make a round trip without revisiting any nodes…

number of cows Input total # of foods total # of drinks # of foods cow[i] likes # of drinks cow[i] likes foodsdrinks 0 Output # of cows that can receive both a food and a drink they like… 3 each can be used only once Likes foodsdrinks What is a cow-satisfying assignment here? dining

number of classes Input # of cows (edges) edge from class 1 to class 2 Output smallest number of projectors needed to cover all classes 2 class are scheduled sequentially… project other edges

See you next week!

Max flow examples… Dinner problem Circuses problem A E C F D B G Circus inspectors need to visit every circus -- starting from anywhere. What is the smallest # of inspectors needed to visit each node without overlap? There are M teams with M[i] team members T tables with T[i] seating capacity No two members from one team should share a table. Can you still seat everyone? tables with capacities team sizes

Martin's approach… Can we compute M 10 faster? 100x100 bit matrix completed at 9 and some others, perhaps submitted during the lab session…

Moo U Input Output # of students maximum number of students that can be fed! # of toppings available # of toppings on each pizza student 1 likes 2 toppings: #2 and #1 The CS 5 pizza problem! student 2 likes 1 topping: #1 student 3 likes 1 topping: #2

Bipartite Matching … students pizzas up to 1,000 up to 30-choose-15 A greedy approach works here!

The Marriage Problem Start with some matching (in red) Find an “augmenting path” From an open vertex in one set to an open vertex in the other set with alternating edges in the current matching (in red) This augmenting path produces a larger match!

Max flow / min cut … students pizzas up to 1,000 up to 30-choose-15 source sink preferences … What is the largest network flow this graph will allow?

This week Look over these two problems… Ideas?

grain Input Output # of weights smallest value that can not be formed from a subset of the weights weights Where are the dead spots?

fliptile Input Output size of board moves to make to turn all of the lights off starting state of the lights (tiles) Lights Out! (lexicographically minimal) Linear algebra approach? Each move flips its own tile and its 4-neighbors…

This week Returning to the other two…

This week

ACM this week: graphs Graph problems, take 1 Today: Graph-algorithm matching challenge Floyd-Warshall all-pairs shortest paths Edgar Dijkstra single-source shortest paths Ford-Fulkerson max-flow min-cut Bellman Ford single-source shortest paths Prim minimum spanning tree Kruskal minimum spanning tree name problem

ACM this week Today: Minimum spanning tree: Given a graph, find the minimum-weight tree within it. Minimum spanning tree political mantra: Graph problems and geometric algorithms, take 1

ACM this week Today: Minimum spanning tree: Given a graph, find the minimum-weight tree within it. Minimum spanning tree political mantra: Greed is good! Graph problems and geometric algorithms, take 1

ACM this week: graphs Graph problems, take 1 Today: Graph-algorithm matching challenge Floyd-Warshall all-pairs shortest paths Edgar Dijkstra single-source shortest paths Ford-Fulkerson max-flow min-cut Bellman Ford single-source shortest paths Prim minimum spanning tree Kruskal minimum spanning tree name problem

All-pairs shortest paths A B E D C A B C D E A BC DE from to “Floyd-Warshall algorithm” D 0 = (d ij ) 0 d ij = shortest distance from i to j through nodes {1, …, k} k d ij = shortest distance from i to j through no nodes 0 Adjacency Matrix

All-pairs shortest paths... D 0 = (d ij ) d ij = shortest distance from i to j through {1, …, k} k “Floyd-Warshall algorithm” Before A B C D E A BC DE D 1 = (d ij ) After A B C D E A BC DE

All-pairs shortest paths... D 0 = (d ij ) A B C D E D 1 = (d ij ) 1 d ij = shortest distance from i to j through {1, …, k} k “Floyd-Warshall algorithm” Before After A B C D E A BC DE A B C D E A BC DE + ) d ij = k d ij k-1, d ik k-1 d kj k-1 min(

All-pairs shortest paths A B C D E D 2 = (d ij ) A B C D E D 3 = (d ij ) A B C D E D 4 = (d ij ) 4 A B C D E D 5 = (d ij ) 5 to store the path, another matrix can track the last intermediate vertex

Thanks to Wikipedia 2007… Floyd Warshall…

and 2008 How would you change this to find longest paths? What has to be true about the graph? by 2009 FW will be a built-in command in Wikipedia pseudocode

New abuse of FW! Suppose your graph is a list of edges def SP( a, b, G ): if a == b: return [ 0.0, b ] if G == []: return [ 1.0e42 ] # infinity minFromA = SP( a, G[0][0], G[1:] ) minTo_b = SP( G[0][1], b, G[1:] ) totalCost = minFrom_a[0] + minTo_b[0] + G[0][2] minRest = SP( a, b, G[1:] ) costRest = minRest[0] if costRest < totalCost: return minRest else: return [ totalCost ] + minFrom_a[1:] + minTo_b[1:] G = [ ["a", "b", 100], ["a", "c", 300], ["b", "c", 42], ["b", "d", 88], ["c", "d", 1] ];

This week's problems… Read over these four problems and provide a relative ranking (and the algorithm you might work with!) difficulty scale (1 easy - 10 ouch!)

lily

mtwalk

ACM today! Jotto, continued: (juniors and sophomores' guesses) FroshSophsJrsSrsOld people pluto 0pluto 2pluto 3pluto 1 pluto 0pluto 2pluto 3pluto 1 A look back (at dynamic programming…) A look forward (graphs!) IOCCC

See you next Tuesday! Lab with new problems…

Class Organization alternating format discussion sessions lab sessions problem and program analysis discussion of strategy and coding tips deciding on functional decomposition, data structures, language facilities, and algorithms to use in teams of 2-3 teams may use 1 machine per person (only the mock contest adheres to ACM rules) these problems count for each member of the group sometimes new problems, other times with known ones ~ 4 problems given out per week… a team might want to practice with only 1 machine

Class Organization Feedback from prior semesters… make individual vs. team-based work clear, lectures vs. labs problems are, in general, individually completed -- except there should be an opportunity to start coding “cold” snacks and jotto! problems per person per week? about 1~2 (if you work on a team in lab) and consider all of the weeks of the term! those done during the lab "mock contest" sessions submit for each person ( me if there are problems…) provide the code to all team members you may or may not choose to work as a team afterwards

Course webpage references administrative info problem statements and sample data problems you have solved

Grading CS 189 is graded individually... (it’s possible to take it P/F, too) Coding Guidelines problems can be done any time during the semester discussion of algorithms always OK coding should be within teams you may use any references except an existing solution or partial solution… one person should take the lead on each problem use /cs/ACM/acmSubmit to submit try things out ! the reason for ACM! though not for CS elective credit…

Problem multipliers Problems are worth double if You solve them during the 4:15 - 5:30 lab sessions It's one of the "extra difficult" problems, which will be determined as we go… The new-language bonus is only in the spring term! Any standard language is OK -- but do keep in mind that the competition allows only Java, C, and C++. Other "standard" languages: the team gets credit, up to 3 people These multipliers may be accumulated… reasonable alternatives will also be considered… C#, python, ruby Language Choice? Ask about our 2 extra- 2-credit projects! web-updating and web-jotto

Spring 2008 summary python 82 java 60 C++ 40 Tallies per problem and per language (thus far)… 17 (+2) 8416 (+2) 1 (+1) 6 (+1) 20 (+12) (+2) 3 (+1) (+1) 1 (+1) 17 (+9) (+2) 4 (+2) (+2) 13 (+10) 14 (+9) 121 (+16) (+4) 1115 (+14) number of 2x scores number of 4x scores d 8 ruby 6 scheme 3 lua 2 awk 2 js 2 sql cobol basic x86 asm pascal mathematica sh, latex 1 each

Jotto! SophsJrsSrsProfs A word-guessing game similar to mastermind… pluot 1pluot 0pluot 1pluot 2

Dynamic programming!

Dynamic programming When a seemingly intractable problem has lots of repeated substructure, go DP! Build a table of partial results. Replace computation with table look-up when possible For example:

Dynamic programming Build a table of partial results. Replace computation with table look-up when possible the binary-decimal problem, for example: Numbers, N, up to 10 6 Input 0 marks the end of the input the smallest decimal multiple of N with only the digits 0 and 1 ! Output Ideas? When a seemingly intractable problem has lots of repeated substructure, go DP!

One way… Count up to the solution, starting from 1… adding digits changes the error (remainder) in predictable ways insight: from CS 60!

Dynamic programming Storing intermediate results in a table for fast look-up: input N = 6 possible remainders upon dividing by N (6) # of digits in answer

input N = 6 possible remainders upon dividing by N (6) # of digits in answer Dynamic programming Storing intermediate results in a table for fast look-up:

input N = 6 possible remainders upon dividing by N (6) # of digits in answer Dynamic programming Storing intermediate results in a table for fast look-up:

input N = 6 possible remainders upon dividing by N (6) # of digits in answer Dynamic programming Storing intermediate results in a table for fast look-up:

input N = 6 possible remainders upon dividing by N (6) # of digits in answer Dynamic programming Storing intermediate results in a table for fast look-up:

DP! Only checking values for which a remainder has not yet been used… Fast

Another example binary-as-decimal problem "pebbles" problem (2007 ACM regionals) Square array, up to 15x15, of integers from 1 to 99 Input Output Idea place "pebbles" on integers, trying to maximize total, but no two pebbles may be adjacent… maximum possible sum 14? vertically, horizontally, or diagonally naïve running time?

Pebbles Square array, up to 15x15, of integers from 1 to 99 Input DP Idea consider all possibilities for pebbling each row - they only depend on the previous row's best scores! Subset chosen (pebbles) Row # abc Store the BEST score available for each possible subset.

Square array, up to 15x15, of integers from 1 to 99 Input DP Idea consider all possibilities for pebbling each row - they only depend on the previous row's best scores! Subset chosen (pebbles) Row # abc Store the BEST score available for each possible subset. 0 68x39xx Pebbles

Square array, up to 15x15, of integers from 1 to 99 Input DP Idea consider all possibilities for pebbling each row - they only depend on the previous row's best scores! Subset chosen (pebbles) Row # abc Store the BEST score available for each possible subset. 0 68x39xx xxx Pebbles

Square array, up to 15x15, of integers from 1 to 99 Input DP Idea consider all possibilities for pebbling each row - they only depend on the previous row's best scores! Subset chosen (pebbles) Row # abc Store the BEST score available for each possible subset. 0 68x39xx xxx xxx 0+13 c +13 b +9 a +9 ? running time? What is the best here? Pebbles

binary-as-decimal problem "pebbles" problem (2007 ACM regionals) Square array, up to 15x15, of integers from 1 to 99 Input Output Idea place "pebbles" on integers, trying to maximize total, but no two pebbles may be adjacent… maximum possible sum 572 code Pebbles

Thanks, Martijn! Scanner sc = new Scanner(System.in); even a bit easier! Martijn is shifty! Martijn is VERY shifty! Where is the table? This sure is sum code… to the max

Problem Set #0 (4 problems) In teams of 2~3, read over these… I need a picture of Farmer Ran!

Problem Set #0 (4 problems) In teams of 2~3, read over these. Where does the structure of the problem depend on similar (but smaller!) substructure? Think of your next 5-letter jotto word… ! How might you build up a table of values toward an overall solution?

See you next Tuesday! bring a laptop, if you have one…

Jotto! SophsJrsSrsMe A word-guessing game similar to mastermind… pluot 1pluot 0pluot 1pluot 2

Problem Set #1 (6 probs, 3 wks) Input 4 tow cat row care....#.....## 0 # of words in the puzzle (to follow) # of rows in the puzzle (after the words) the words the puzzle this indicates the end of the input…

Problem Set #1 (6 probs, 3 wks) Input 4 tow cat row care....#.....## 0 either the solution OR a statement that it can't be solved… Output Problem 1 cat a#o row e## Problem 2: no layout is possible.

Problem Set #1 (6 probs, 3 wks) Input # of empty boxes on the form # of clerks in the office (three lines each) clerk #0 this indicates the end of the input… the box(es) CHECKED the box(es) ERASED the clerks who get a copy clerk #1 clerk #2 clerk #3 clerk # the form

Problem Set #1 (6 probs, 3 wks) Input # of empty boxes on the form # of clerks in the office (three lines each) clerk #0 this indicates the end of the input… the box(es) CHECKED the box(es) ERASED the clerks who get a copy clerk #1 clerk #2 clerk #3 clerk # the form let's try it…

Problem Set #1 (6 probs, 3 wks) Input # of empty boxes on the form # of clerks in the office (three lines each) clerk #0 this indicates the end of the input… the box(es) CHECKED the box(es) ERASED the clerks who get a copy clerk #1 clerk #2 clerk #3 clerk # the form Output the boxes checked the last time it leaves clerk #0's desk…

Problem Set #1 (6 probs, 3 wks) Input RDDR Speedy M 0101 Jumper F 0101 Slowpoke M 1101 Terror F 1100 Shadow F 1001 *** Frisky 0101 Sleepy 1101 *** list of traits, R == "recessive" D == "dominant" D traits are passed if EITHER parent has them R traits are passed if BOTH parents have them all of the parents, gender, and traits the baby shrews… Deduce their possible parents!

Problem Set #1 (6 probs, 3 wks) Input RDDR Speedy M 0101 Jumper F 0101 Slowpoke M 1101 Terror F 1100 Shadow F 1001 *** Frisky 0101 Sleepy 1101 *** list of traits, R == "recessive" D == "dominant" D traits are passed if EITHER parent has them R traits are passed if BOTH parents have them all of the parents, gender, and traits the baby bunnies… Deduce their possible parents! Output Frisky by Jumper-Slowpoke or Jumper-Speedy or ______ Sleepy by _________

Problem Set #1 (6 probs, 3 wks) Input RDDR Speedy M 0101 Jumper F 0101 Slowpoke M 1101 Terror F 1100 Shadow F 1001 *** Frisky 0101 Sleepy 1101 *** list of traits, R == "recessive" D == "dominant" D traits are passed if EITHER parent has them R traits are passed if BOTH parents have them all of the parents, gender, and traits the baby bunnies… Deduce their possible parents! Output Frisky by Jumper-Slowpoke or Jumper-Speedy or Shadow-Speedy Sleepy by Shadow-Slowpoke

Problem Set #1 (6 probs, 3 wks) Decide which problem is the easiest and which one is the hardest … (to code, not to compute!) Read these three problems… then

Problem Set #1 (6 probs, 3 wks) my estimates… hardest easiest important heuristic: I’m always wrong

See you next Tuesday in the CS labs… !

Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting knuth (or turing or…) installing Debian 3.1 Engineering dept. the dumpster University of St. Petersburg On the 405, in traffic, being chased by police (and TV) helicopters. Mailing something at the Claremont Post Office Waiting for the snow enveloping you on Route 5 N to melt Krispy Kreme’s drive through Teaching Honors English for Janice Barbee at Pomona High School Worldcom Headquarters Leading a Gray Davis / Gary Coleman / Arnold “T-800” Schwarzenegger gubernatorial fundraiser exploring martian soil Being dragged off-course 18 miles into a marathon race by a crazed spectator Massey University Palmerston North, NZ Pittsburgh Driving N on the Dalton Highway… (though it feels like it!)

What is this course about? A chance to “improve” your programming skills Algorithm analysis and insight Program design and implementation optimizing coding time ACM programming contest What Why Research/prototype programming Hands-on practice with algorithms and techniques Unofficial course name: CS -70 Familiarity with Java’s libraries OR your choice of language

Course Organization Jan 16 Welcome! Random teams of 3: 6 problems, 3 weeks Jan 23 Lab session to work on problems (Beckman B102 or 105) Jan 30 Discussion session on the first set of problems Feb 6 Lab session with new problems: 4 problems, 2 weeks Feb 13 Discussion session on the second set of problems Feb 20 Lab session with new problems: 6 problems, 3 weeks Feb 27 Discussion session on the third set of problems Mar 6 No class - Fall break Mar 20 Mock ACM contest, 9pm – 1am, teams of 3, 6 pr, 4 hours Mar 27 No class (out of town) Apr 3 Discussion session on the mock contest + Finale! You may submit problems until the end of exams… 2 per team 2/team 3 per team 1-4 / team

Class Organization alternating format discussion sessions lab sessions problem and program analysis discussion of strategy and coding tips deciding on functional decomposition, data structures, language facilities, and algorithms to use in teams of 2-3 teams should use 1 terminal per person (only the mock contest adheres to ACM rules) these problems count for each member of the group sometimes new problems, other times with known ones ~1 problem per week per person…

Course webpage reference links administrative info problem statements and test data problems your team has solved

Grading CS 189 is graded individually... (it’s possible to take it P/F, too) Coding Guidelines problems can be done any time during the semester discussion of algorithms always OK coding should be within teams you may use any references except an existing solution or partial solution… one person should take the lead on each problem use /cs/ACM/acmSubmit to submit try things out ! the reason for ACM!

Choose your language… extensive library of data structures and algorithms available Java is almost the universal choice for the competition… I/O made simpler with 1.5’s Scanner and printf the C in CS! Input from stdin Output to stdout

Choose your language… Python is niceC# Whatever language you choose needs to be able to run on the Macs in the CS labs (and preferably knuth, as well…) I’ll likely need your help to get things set up for testing… def floyd_warshall(W, infinity): n = matrix.get_num_rows(W) D = matrix.clone(W) DD = matrix.make(n,n) for k in xrange(n): for i in xrange(n): for j in xrange(n): DD[i][j] = min(D[i][j], D[i][k] + D[k][j]) DD, D = D, DD return D Others ? Marty: prolog!

Problem Set #1 (6 probs, 3 wks) Input 4 tow cat row care....#.....## 0 # of words in the puzzle (to follow) # of rows in the puzzle (after the words) the words the puzzle this indicates the end of the input…

Problem Set #1 (6 probs, 3 wks) Input # of empty boxes on the form # of clerks in the office (three lines each) clerk #0 this indicates the end of the input… the box(es) CHECKED the box(es) ERASED the clerks who get a copy clerk #1 clerk #2 clerk #3 clerk # the form Output the boxes checked the last time it leaves clerk #0's desk…

Problem Set #1 (6 probs, 3 wks) Input RDDR Speedy M 0101 Jumper F 0101 Slowpoke M 1101 Terror F 1100 Shadow F 1001 *** Frisky 0101 Sleepy 1101 *** list of traits, R == "recessive" D == "dominant" D traits are passed if EITHER parent has them R traits are passed if BOTH parents have them all of the parents, gender, and traits the baby shrews… Deduce their possible parents! Output Frisky by Jumper-Slowpoke or Jumper-Speedy or ______ Sleepy by _________

Problem Set #1 (6 probs, 3 wks) Decide which problem is the easiest and which one is the hardest … (to code, not to compute!) Read these three problems… then

Coaches’ Room

Choose your language… extensive library of data structures and algorithms available Java/Cthe universal choice for the competition… I/O made simpler with 1.5’s Scanner and printf the C in CS! Input from stdin Output to stdout

Choose your language… Python is nice def floyd_warshall(W, infinity): n = matrix.get_num_rows(W) D = matrix.clone(W) DD = matrix.make(n,n) for k in xrange(n): for i in xrange(n): for j in xrange(n): DD[i][j] = min(D[i][j], D[i][k] + D[k][j]) DD, D = D, DD return D Ruby :-) Marty: prolog! Postscript!

Welcome to Programming Practicum “Putting the C into CS” You aren’t here writing clinic reports clinic liaison phone call coding chunky strings rebooting knuth (or turing or…) installing Debian 3.1 Engineering dept. the dumpster University of St. Petersburg On the 405, in traffic, being chased by police (and TV) helicopters. Mailing something at the Claremont Post Office Waiting for the snow enveloping you on Route 5 N to melt Krispy Kreme’s drive-through Teaching Honors English for Janice Barbee at Pomona High School Worldcom Headquarters Leading a Gray Davis / Gary Coleman / Arnold “T-800” Schwarzenegger gubernatorial fundraiser exploring martian soil Being dragged off-course 18 miles into a marathon race by a crazed spectator Massey University Palmerston North, NZ Pittsburgh Driving N on the Dalton Highway… (though it feels like it!) Victorville, for DARPA's Urban Granc Challenge Waiting in line to vote in the Florida primaries…

What is this course about? A chance to “improve” your programming skills Algorithm analysis and insight Program design and implementation optimizing coding time ACM programming contest What Why Research/prototype programming Hands-on practice with algorithms and techniques Unofficial course name: CS -70 Familiarity with Java’s libraries OR your choice of language

Class Organization alternating format discussion sessions lab sessions problem and program analysis discussion of strategy and coding tips deciding on functional decomposition, data structures, language facilities, and algorithms to use in teams of 2-3 teams should use 1 machine per person (only the mock contest adheres to ACM rules) these problems count for each member of the group sometimes new problems, other times with known ones ~3 problems per week per person…

Class Organization Feedback from prior semesters… make individual vs. team-based work clear, lectures vs. labs problems are, in general, individually completed, except there should be an opportunity to start coding “cold” snacks and jotto! problems per person per week? ~2 in the fall ~3 in the spring those done during the lab "mock contest" sessions submit for each person (or me…) provide the code to all team members you may or may not choose to work as a team afterwards

Course Organization Jan 29 Welcome! Review of dynamic programming: 4 problems Feb 5 Lab/Mock contest session: 4 problems Feb 12 Discussion session on geometry problems: 4 problems Feb 19 Lab/Mock contest session: 4 problems Feb 26 Lab/Mock contest session: 4 problems Mar 4 Discussion session on search problems: 4 problems Mar 11 No class… need to be away Mar 18 No class - Spring break Mar 23 Mock ACM contest, 9pm – midnight, 6 problems Mar 25 Discussion and wrap-up of the semester You may submit problems until the end of exams… Sat. Mar 8 and Sat. Apr 19 external competitions…

Competition Options Sat. Mar 8 and Sat. Apr 19 external competitions…

Course webpage references administrative info problem statements and test data problems you have solved

Grading CS 189 is graded individually... (it’s possible to take it P/F, too) Coding Guidelines problems can be done any time during the semester discussion of algorithms always OK coding should be within teams you may use any references except an existing solution or partial solution… one person should take the lead on each problem use /cs/ACM/acmSubmit to submit try things out ! the reason for ACM!

Problem multipliers Problems are worth double if You solve them during the 4:15 - 5:30 lab sessions You are the first person to use a particular language - though there is an additional responsibility here: to set up the testing system to handle that language! It's one of the "extra difficult" problems, which will be determined as we go… languages already used: the team gets credit, up to 3 people python 56 ruby 12 java 6 c++ 11 perl 2 postscript 2 c# 8 haskell 1 prolog 2 c 5 php 1 These multipliers may be accumulated…

Dynamic programming When a seemingly intractable problem has large amounts of repeated or redundant substructure, DP can sometimes provide an efficient solution. Build a table of partial results. Replace computation with table look-up when possible For example: Numbers, N, up to 10 6 Input 0 marks the end of the input the smallest decimal multiple of N with only the digits 0 and 1 ! Output Ideas?

One way… Count up to the solution, starting from 1…

Dynamic programming Storing intermediate results in a table for fast look-up: input N = 6 possible remainders upon dividing by N (6) # of digits in answer

DP! Only checking values for which a remainder has not yet been used…

Problem Set #1 (4 problems) In teams of ~3, think about - how would you solve this problem? - how could you most simplify the programming ? - think of a 5-letter jotto word… ! - is it a dynamic programming problem? - divide up with one problem per group -

Competition Options Sat. Mar 8 and Sat. Apr 19 external competitions…