acm today some nice unix commands… practice problems? code.google.com/codejam/ this week: beyond...
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!
screenscreen -r
to startto 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 Contest @ 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…
Sophs Jrs Srs Others
icily 0 icily 0 icily 1 icily 1
strep 2 strep 2 strep 2 strep 1
spork 1 spork 3 spork 0 spork 0
spend 2 spend 2 spend ? spend 2
peeps 2 peeps 1 peeps ? peeps 1
furls 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
C13
F
16
10 4 9
12
14
7
20
4source
capacity
sink
The problem how much traffic can get from the source to the sink ?
Ford-Fulkerson algorithm
http://www-b2.is.tokushima-u.ac.jp/~ikeda/suuri/maxflow/MaxflowApp.shtml?demo1Some animations:
http://www.lix.polytechnique.fr/~durr/MaxFlow/
Max FlowThe problem how much traffic can get from the source to the sink ?
A
B
E
D
C13
AB
C
D
E
FROM
A B C D E
F
- 16 13 - -- - 10 12 -
- 4 - - 14
- - 9 - -
- - - 7 -
--
-
20
4
- - - - - -F
F
16
10 4 9
12
14
7
20
4
TO
“Capacity Graph”
source
sink
capacity C
Find a path in C via BFSThe problem how much traffic can get from the source to the sink ?
A
B
E
D
C13
FROM
F
- 16 13 - -- - 10 12 -
- 4 - - 14
- - 9 - -
- - - 7 -
--
-
20
4
- - - - - -
16
10 4 9
12
14
7
20
4
TO
source
sink
capacity CAB
C
D
E
A B C D E
F
F
need to add this into here…
Create FCreate a FLOW GRAPH with the minimum weight from that
path
A
B
E
D
C13
AB
C
D
E
FROM
A B C D E
F
- 12 0 - --12
- 0 12 -
- 0 - - 0
- -12
0 - -
- - - 0 -
--
-
12
0
- - - -12
- -F
F
16
10 4 9
12
14
7
20
4
TO
“Flow Graph”
source
sink
capacity F
12
12
12
flow in one direction is negative flow in the other direction
R = C - FCreate a RESIDUAL GRAPH with the rest of the capacity
after that flow
A
B
E
D
C13
AB
C
D
E
FROM
A B C D E
F
F
F
4
10 4 9
0
14
7
8
4
TO
“Residual Graph”
source
sink
capacity R
12 12
reverse edges allow the "undoing" of previous flow!
12
- 4 13 - -12 - 10 0 -
- 4 - - 14
- 12 9 - -
- - - 7 -
--
-
8
4
- - - 12 - -
Keep going!Continue running this on the residual capacity until BFS
fails…
A
B
E
D
C12/13
F
11/16
0/10
1/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
C13
F
16
10 4 9
12
14
7
20
4
“Residual Graph”
source
sink
capacity
4
3
2
1
5
2
2
10
4
flow
Don't need to keep R around explicity: Keep only the current flow (F) and the
original capacity (C).A
B
C
D
EF
2
18
4
3 residual
9
5
9
72592
11
124
61
Floyd-Fulkerson
1. Set F to all 02. Compute R = C - F3. 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_karpThis 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 ?
http://www-b2.is.tokushima-u.ac.jp/~ikeda/suuri/maxflow/MaxflowApp.shtml?demo1Some animations:
http://www.lix.polytechnique.fr/~durr/MaxFlow/
A
B
E
D
C13
F
16
10 4 9
12
14
7
20
4source
capacity
12
12
12
The challenge:
setting up the MaxFlow graph
dinner
4 54 5 3 53 5 2 6 44 54 5 3 53 5 2 6 30 0
number of teams Input
Output
number of tables
# of people in each team
can an assignment be made without putting teammates
together?
01
capacity of each table
again…
end…
35
2 6 3
tables with capacities
teams with sizes
53
4
5
seating assignments!
no teammates
patrol
6 71 22 61 33 43 54 65 6
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)
1
1 6
2
34
5
start (farm) goal (ice cream)
Bessie must make a round trip without revisiting any nodes…
4 3 32 2 1 2 3 12 2 2 3 1 22 2 1 3 1 22 1 1 3 3
number of cows
Input
total # of foods
total # of drinks
# of foods cow[i] likes
# of drinks cow[i] likesfoods drinks
0
Output
# of cows that can receive both a food and a
drink they like…
3
each can be used only once
Likes
foods drinks
1
2
3
1 2
2 3
1 3
1 3
3 1
1 2
1 2
3What 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
4 41 22 32 41 4
other edges
1 2 3 4
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?
35
2 6 3
tables with capacities
team sizes
4 5 3 5
Martin's approach…
Can we compute M10 faster?
100x100 bit matrix
completed at
9
and some others, perhaps
submitted during the lab session…
Moo U.
3 2 12 2 11 11 2
2
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
…
studentspizzas
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 setwith alternating edges in the current matching (in red)This augmenting path produces a larger match!
Max flow / min cut
…
studentspizzas
up to 1,000
up to 30-choose-15
sourcesink
preferences…
1
1
11
1
1
1
11
1
1
1
1
What is the largest network flow this graph
will allow?
This week
Look over these two problems…
Ideas?
grain
5113411
10
Input
Output
# of weights
smallest value that can not be formed from a subset of the
weights
weights
Where are the dead spots?
fliptile
4 41 0 0 10 1 1 00 1 1 01 0 0 1 0 0 0 0
1 0 0 11 0 0 10 0 0 0
Input
Output
size of board
moves to make to turn all of the
lights offstarting state of the
lights (tiles)
Lights Out!
http://www.csm.ornl.gov/~geist/java/applets/lightsout/
(lexicographically minimal)
Linear algebra approach?http://mathworld.wolfram.com/LightsOutPuzzle.html
Each move flips its own tile and its
4-neighbors…
This week
Returning to the other two…
This week
This week
ACM this week: graphs
Graph problems, take 1Today:
Graph-algorithm matching challenge
Floyd-Warshall all-pairs shortest pathsEdgar Dijkstra single-source shortest pathsFord-Fulkerson max-flow min-cut
Bellman Ford single-source shortest pathsPrim minimum spanning treeKruskal 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 1Today:
Graph-algorithm matching challenge
Floyd-Warshall all-pairs shortest pathsEdgar Dijkstra single-source shortest pathsFord-Fulkerson max-flow min-cut
Bellman Ford single-source shortest pathsPrim minimum spanning treeKruskal minimum spanning tree
name problem
All-pairs shortest paths
A
B
ED
C
8
13
1
6
12
9
7 0
11
0 8 13 - 1- 0 - 6 12
- 9 0 - -
7 - 0 0 -
- - - 11 0
AB
C
D
E
A B C D E
from
to
“Floyd-Warshall algorithm”
D0 = (dij )
0
dij = shortest distance from i to j through nodes {1, …, k}
k
dij = shortest distance from i to j through no nodes
0
Adjacency Matrix
All-pairs shortest paths...
D0 = (dij )
0
0 8 13 - 1- 0 - 6 12
- 9 0 - -
7 - 0 0 -
- - - 11 0
dij = shortest distance from i to j through {1, …, k}
k
“Floyd-Warshall algorithm”
BeforeAB
C
D
E
A B C D E
D1 = (dij )
1
0 8 13 - 1- 0 - 6 12
- 9 0 - -
7 15 0 0 8
- - - 11 0
AfterAB
C
D
E
A B C D E
All-pairs shortest paths...
D0 = (dij )
0
0 8 13 - 1- 0 - 6 12
- 9 0 - -
7 - 0 0 -
- - - 11 0
AB
C
D
E
D1 = (dij )
1
dij = shortest distance from i to j through {1, …, k}
k
0 8 13 - 1- 0 - 6 12
- 9 0 - -
7 15 0 0 8
- - - 11 0
“Floyd-Warshall algorithm”
Before AfterAB
C
D
E
A B C D E
AB
C
D
E
A B C D E
+ )
dij
=
k dij
k-1, dik
k-1 dkj
k-1min(
All-pairs shortest paths...
0 8 13 14 1- 0 - 6 12
- 9 0 15 21
7 15 0 0 8
- - - 11 0
AB
C
D
E
D2 = (dij )
2
0 8 13 14 1- 0 - 6 12
- 9 0 15 21
7 9 0 0 8
- - - 11 0
AB
C
D
E
D3 = (dij )
3
0 8 13 14 113 0 6 6 12
22 9 0 15 21
7 9 0 0 8
18 20 11 11 0
AB
C
D
E
D4 = (dij )
4
AB
C
D
E
D5 = (dij )
5
to store the path, another matrix can track the last intermediate vertex
0 8 12 12 113 0 6 6 12
22 9 0 15 21
7 9 0 0 8
18 20 11 11 0
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)
Frosh Sophs Jrs Srs Old people
pluto 0
pluto 2
pluto 3
pluto 1
pluto 1
pluto 0
pluto 2
pluto 3
pluto 1
pluto 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 (email 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 <file> 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)
8 4 16 (+2)
1 (+1)
6 (+1)
20 (+12)
(+2)
3 (+1)
1 1 2 11 (+1)
1 (+1)
17 (+9)
(+2)
4 (+2)
1
2 2 8 3 2 8 (+2)
13 (+10)
14 (+9)
1 21 (+16)
(+4)
1 1 15 (+14)
number of 2x scores number
of 4x scores
d 8
ruby 6
scheme 3
lua 2
awk 2
js 2
sqlcobolbasicx86 asmpascalmathematicash, latex
1each
Jotto!
Sophs Jrs Srs Profs
A word-guessing game similar to mastermind…
pluot 1 pluot 0 pluot 1 pluot 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:
263190
Numbers, N, up to 106
Input
0 marks the end of the input
10111011111001
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
0 1 2 3 4 5
2
1
3
4
input N = 6
possible remainders upon dividing by N (6)
# of digits in answer
0 1 2 3 4 5
2
1
3
4
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
0 1 2 3 4 5
2
1
3
4
1
10 111
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
0 1 2 3 4 5
2
1
3
4
1
111110 10 111
10 111
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
0 1 2 3 4 5
2
1
3
4
1
111110 10 111
10 111
1110 111110 10 111
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?
3 8 6 7 9 1 4 6 1
vertically, horizontally, or diagonally
3 8 67 9 14 6 1
naïve running time?
Pebbles
3 8 67 9 14 6 1
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)
000 001 010 011 100 101 110 111Row #
0
1
2a b c
Store the BEST score available for each possible subset.
3 8 67 9 14 6 1
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)
000 001 010 011 100 101 110 111Row #
0
1
2a b c
Store the BEST score available for each possible subset.
0 6 8 x 3 9 x x
Pebbles
3 8 67 9 14 6 1
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)
000 001 010 011 100 101 110 111Row #
0
1
2a b c
Store the BEST score available for each possible subset.
0 6 8 x 3 9 x x
90+9
41+3
99+0
137+6
88+0
x x x
Pebbles
3 8 67 9 14 6 1
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)
000 001 010 011 100 101 110 111Row #
0
1
2a b c
Store the BEST score available for each possible subset.
0 6 8 x 3 9 x x
90+9
41+3
99+0
137+6
88+0
x x x
x x x0+13 c+13 b+9 a+9 ?
running time?
What is the best here?
Pebbles
binary-as-decimal problem
"pebbles" problem (2007 ACM regionals)
71 24 95 56 5485 50 74 94 2892 96 23 71 1023 61 31 30 4664 33 32 95 89
Square array, up to 15x15, of integers
from 1 to 99
Input
Output
71 24 95 56 5485 50 74 94 2892 96 23 71 1023 61 31 30 4664 33 32 95 89
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!
Sophs Jrs Srs Me
A word-guessing game similar to mastermind…
pluot 1
pluot 0
pluot 1
pluot 2
Problem Set #1(6 probs, 3 wks)
Input
4 4 tow cat row care ... .#. ... .## 0 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 4 tow cat row care ... .#. ... .## 0 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
6 5 1
1 2 2 3 4 4 5 1 3 2
1 4 2 1 0 0 0
# 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 #4
0 1 2 3 4 5
the form
Problem Set #1(6 probs, 3 wks)
Input
6 5 1
1 2 2 3 4 4 5 1 3 2
1 4 2 1 0 0 0
# 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 #4
0 1 2 3 4 5
the form
let's try it…
Problem Set #1(6 probs, 3 wks)
Input
6 5 1
1 2 2 3 4 4 5 1 3 2
1 4 2 1 0 0 0
# 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 #4
0 1 2 3 4 5
the form
Output1 3 4 5
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 themR 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 themR 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 themR 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-Speedyor Shadow-SpeedySleepy 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 skillsAlgorithm analysis and
insightProgram 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 problemsFeb 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 breakMar 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 <file> 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 nice
C#
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 4 tow cat row care ... .#. ... .## 0 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
6 5 1
1 2 2 3 4 4 5 1 3 2
1 4 2 1 0 0 0
# 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 #4
0 1 2 3 4 5
the form
Output1 3 4 5
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 themR 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…
Waiting in line to vote in the Florida primaries…
What is this course about?
• A chance to “improve” your programming skillsAlgorithm analysis and
insightProgram 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 email 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 problemsFeb 5 Lab/Mock contest session: 4 problems
Feb 12 Discussion session on geometry problems: 4 problemsFeb 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 breakMar 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 19external
competitions…
Competition Options
www.ccsc.org/southwestern/2008/contest.html
www.ieee.org/web/membership/students/scholarshipsawardscontests/ieeextreme.html
Sat. Mar 8 and Sat. Apr 19external
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 <file> 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:
263190
Numbers, N, up to 106
Input
0 marks the end of the input
10111011111001
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
0 1 2 3 4 5
2
1
3
4
1
111110 10 111
10 111
1110 111110 10 111
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
www.ccsc.org/southwestern/2008/contest.html
www.ieee.org/web/membership/students/scholarshipsawardscontests/ieeextreme.html
Sat. Mar 8 and Sat. Apr 19external
competitions…