-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslide24-32notes.Rmd
1418 lines (1016 loc) · 49.5 KB
/
slide24-32notes.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Slide Notes: 24-32"
author: "David J. Hunter"
output:
html_document:
toc: true
toc_float:
collapsed: false
smooth_scroll: true
df_print: paged
theme: spacelab
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(comment = NA)
```
This page contains the content of all the slides for the material that we covered in Chapters 7,8,10, and 11 of [Algorithms](http://jeffe.cs.illinois.edu/teaching/algorithms/book/Algorithms-JeffE.pdf), by Jeff Erickson. If you notice any errors, please [create a new issue](https://github.com/djhunter/algorithms/issues).
# Trees
## Applications of Trees
- Binary search trees
- Recursion trees
- DFS and BFS trees
- Binary heaps
- Huffman Codes
- etc.
Most of these trees had a preferred *root*, and a preferred *direction* (away from the root).
## Tree: General Definition
> A **tree** is a connected, acyclic graph.
By default, a generic tree is *undirected*. To understand this definition, we need to be precise about the meaning of *acyclic*.
- A **walk** in an undirected graph $G$ is a sequence of vertices, where each
adjacent pair of vertices are adjacent in $G$.
- A walk is **closed** if it starts and ends at the same vertex.
- A walk is called a **path** if it visits each vertex at most once.
- A **cycle** is a closed walk that enters and leaves each vertex at most once.
- An undirected graph is **acyclic** if no subgraph is a cycle.
## Unravel the definitions
1. Draw an example of a walk that is not a path.
2. Draw an example of a closed walk that is not a cycle.
3. What is a closed path? Can you draw an example?
4. Draw a tree with 6 vertices. How many edges does it have?
5. How many edges does a tree with $n$ vertices have? Can you prove your answer?
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(3122021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
# Paths in trees
## Unique Paths
**Lemma.** Suppose $T$ is a tree, and $u$ and $v$ are two vertices in $T$. Then there is a unique path from $u$ to $v$.
- There exists a path from $u$ to $v$ because $T$ is connected.
- Suppose to the contrary that there are two different paths from $u$ to $v$.
- Path 1: $a_0 = u, a_1, a_2, \ldots, a_k = v$.
- Path 2: $b_0 = u, b_1, b_2, \ldots, b_j = v$.
- Let $a_s = b_s$ be the last vertex at the start of these paths that are the same.
- Let $a_{k-e} = b_{j-e}$ be the first vertex at the end of these paths that are the same.
- Then $a_s, \ldots, a_{k-e}, b_{j-e-1}, \ldots, b_s$ is a cycle, contradicting that $T$ is a tree.
## Equivalent Condition
The converse of the Lemma is also true: If $G$ is a graph with the property that every pair of vertices are joined by a unique path, then $G$ is a tree.
- Connected: $\checkmark$
- Acyclic: A cycle would contradict the unique path condition.
# Weighted Graphs
## Weighted Edges
A graph is called *weighted* if there is an assignment of real numbers (weights) to the edges. For example,
- Cost function in a network.
- Distance function in a spatial arrangement.
## Minimum Spanning Tree of a Weighted Graph
Given a weighted graph $G$, a **minimum spanning tree** $T$ is a subgraph of $G$ such that:
- $T$ contains all the vertices of $G$, and
- The sum of weights of the edges of $T$ is as small as possible.
6. Why do the above two conditions guarantee that $T$ is a tree?
7. Draw an example of a weighted graph with two different minimum spanning trees (if possible).
8. Draw an example of a weighted graph with a unique smallest edge $e$, such that the minimum spanning tree does not contain $e$ (if possible).
# Uniqueness
## Minimum spanning is unique (almost)
**Lemma.** If all edge weights in a connected graph $G$ are distinct, then $G$ has a unique minimum spanning tree.
- Suppose $G$ has two minimum spanning trees $T$ and $T'$.
- Let $e$ be the smallest edge in $(T\setminus T')\cup(T'\setminus T)$.
- WLOG, $e\in T\setminus T'$.
- Adding this edge to $T'$ creates a cycle.
- One of the edges in this cycle is not in $T$.
- Exchange this edge for $e$, and you reduce the weight of $T'$, a contradiction.
# Minimum Spanning Trees
# Trees
## Tree: Definition and equvalent notions
A **tree** is a *connected*, *acyclic* graph. (By default, a generic tree is *undirected*.) Equivalently,
- *Unique paths:* A tree is an undirected graph $T$ such that, for any two vertices $u$ and $v$ in $T$, there is a unique path from $u$ to $v$.
- *$V-1$ edges:* A tree is a connected, undirected graph with $V-1$ edges.
- *Can't add an edge:* Adding an edge to a tree makes a cycle.
## Minimum Spanning Tree of a Weighted Graph
- A graph is called *weighted* if there is an assignment of real numbers (weights) to the edges.
- Given a weighted graph $G$, a **minimum spanning tree** $T$ is a subgraph of $G$ such that:
- $T$ contains all the vertices of $G$, and
- The sum of weights of the edges of $T$ is as small as possible.
- [Applications](https://en.wikipedia.org/wiki/Minimum_spanning_tree#Applications): network optimization, image recognition, data analysis, etc.
(See Jamboard from last time.)
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(3222021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Smallest edge
1. Let $G$ be a weighted graph with an edge $e$ that is lighter (i.e., smaller) than all the other edges. Prove that any minimum spanning tree must contain $e$.
Hints:
- Suppose to the contrary that $T$ is a minimum spanning tree of $G$ and that ___________________.
- What happens if you add an edge to $T$?
- Show you can make a lighter spanning tree (contradiction).
# Uniqueness
## Simplifying assumption: distinct weights
Without losing generality, we can *assume our edge weights are distinct.*
Why is this OK?
- In most applications, they are distinct.
- We could break ties by adding an insignificant $\varepsilon$ to a weight.
- We could break ties some other systematic way.
- Two floats are "never" equal (at least you shouldn't expect them to be).
```{r}
sqrt(3)^2 == 3
```
## Two minimum spanning trees?
Suppose a connected, weighted, undirected graph $G$ has *distinct edge weights* and *two minimum spanning trees* $T$ and $T'$.
>- Suppose to the contrary that $T \neq T'$.
> - Then there are edges in $T$ that are not in $T'$, and edges in $T'$ that are not in $T$. Let $e$ be the smallest of these edges.
> - In other words, $e$ is the smallest edge in $(T\setminus T')\cup(T'\setminus T)$.
> - WLOG, $e\in T\setminus T'$.
>- Adding this edge to $T'$ creates a cycle in $T'$.
> - One of the edges in this cycle is not in $T$.
> - Exchange this edge for $e$, and you reduce the weight of $T'$, a contradiction.
## **The** minimum spanning tree
We have proved the following.
**Lemma.** If all the edge weights of a graph are distinct, then its minimum spanning tree is *unique*.
So we will henceforth refer to "the" minimum spanning tree of a graph.
# Edge Classification
## Intermediate spanning forests
- We can build a spanning tree by selecting edges.
- At each stage, we avoid cycles, so we have a forest (maybe not a tree).
An *intermediate spanning forest* of a weighted graph $G$ is a subgraph of the minimum spanning tree of $G$.
## Safe and Useless edges
For any intermediate spanning forest $F$ of a graph $G$,
- An edge of $G$ is **useless** if it is not an edge of $F$, but both its endpoints are in the same component of $F$.
- An edge of $G$ is **safe** if it is the minimum-weight edge with exactly one endpoint in some component of $F$.
## Example
In the following graph $G$, the bold edges form an intermediate spanning forest $F$.
<center>

</center>
## Safe and Useless
2. Identify all the safe edges and all the useless edges.
3. What happens if you add a useless edge to $F$?
4. Add all the safe edges to $F$. Is the resulting forest $F'$ still an intermediate spanning forest?
5. Repeat: Add all of the safe edges of $F'$ to $F'$, and continue. How will this process terminate?
# Borůvka's MST Algorithm
# Assignment Comments, Sample Solutions
## MST with largest edge
1. Give an example of a weighted undirected graph that is not a tree, but whose minimum spanning tree contains the largest edge in the graph.
```
1.1
0--------0
6.7/ \ \2.4
/ \5.2 0
0 \ /2.3
0-----0
3.3
```
## Largest cycle edge excluded
2. Let $G$ be a weighted, undirected graph. Prove that for any cycle in $G$, the minimum spanning tree *does not include* the largest edge in the cycle.
(Common wrong answer on Jamboard.)
## Proof considering components (sketch)
- Suppose there exists a minimum spanning tree $T$ that includes a maximum edge $e_\text{max} = uv$ of some cycle. Remove $e_\text{max}$ from $T$.
- The tree is no longer a minimum spanning tree but instead two components, one containing $u$ and the other containing $v$. But since there was a cycle in $G$ containing $e_{max}$, there is a path in $G$ from $u$ to $v$. Therefore, some edge $e$ on this path must connect the two components.
- Exchange $e$ and $e_\text{max}$, contradicting minimality.
## Disprove with a counterexample
3. Prove or disprove: The minimum spanning tree of a weighted, undirected graph $G$ includes the smallest edge in *every* cycle in $G$.
```
(10) (3) (11)
e --------- a --- b ----------- d
\ \ / /
\_ (2) \ / (1) _/
\ c /
\_ _/
\ /
(16) \_ _/ (15)
\ /
\_ _/
\ /
\_ _/
f
```
# Safe and Useless
## Minimum Spanning Tree of a Weighted Graph
- Given a weighted graph $G$, a **minimum spanning tree** $T$ is a subgraph of $G$ such that:
- $T$ contains all the vertices of $G$, and
- The sum of weights of the edges of $T$ is as small as possible.
- An *intermediate spanning forest* is a subgraph of the MST.
For any intermediate spanning forest $F$ of a graph $G$,
- An edge of $G$ is **useless** if it is not an edge of $F$, but both its endpoints are in the same component of $F$.
- An edge of $G$ is **safe** if, in some component of $F$, it is the minimum-weight edge with exactly one endpoint in the component.
## Prim's Theorem
**Theorem.** Let $F$ be an intermediate spanning forest of a weighted graph $G$, and suppose $e$ is a safe edge. Then the minimum spanning tree contains $e$.
>- Let $C$ be the component of $F$ that $e$ is "safe" for, so $e$ has an endpoint in $C$ and an endpoint in $G \setminus C$, and $e$ is the smallest such edge.
>- Suppose to the contrary that the minimum spanning tree $T$ does not contain $e$. The endpoints $u$ and $v$ of $e$ must be connected by a path in $T$, and since exactly one of the endpoints of $e$ is in $C$, one of the edges $e'$ of this path must have an endpoint in $C$ and an endpoint not in $C$.
>- Removing $e'$ from $T$ creates a spanning forest with two components, one containing $u$ and another containing $v$. Adding $e$ to this forest connects these components, and so creates a tree. But this new tree has smaller total weight than $T$, because $e$ is smaller than $e'$. That's a contradiction.
## Greedy MST Meta-Algorithm
Let $G$ be a weighted graph with vertex set $V$ and edge set $E$.
```{javascript, eval=FALSE}
MetaMST(V,E)
F = (V, ∅)
while F is not a tree
add a safe edge to F // NOTE: This choice needs to be specified!!
return F
```
(See Jamboard from last time.)
# Borůvka's Algorithm for the minimum spanning tree
## General idea
Use `MetaMST`, but add *all* the safe edges inside the `while`-loop.
```{javascript, eval=FALSE}
MetaMST(V,E)
F = (V, ∅)
while F is not a tree
add a safe edge to F // NOTE: This choice needs to be specified!!
return F
```
In order to analyze the time, we need to specify how the safe edges are located.
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(3242021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Label the vertices with their component number
```{javascript, eval=FALSE}
CountAndLabel(G): LabelOneComponent(s,count):
count <- 0 Enqueue(s)
for all vertices v while the queue is not empty
unmark v v <- Dequeue
for all vertices v if v is unmarked
if v is unmarked mark v // Line #1
count <- count + 1 v.comp <- count
LabelOneComponent(v, count) for each edge vw
return count Enqueue(w) // Line #2
```
Suppose $G$ has $V$ vertices and $E$ edges.
1. What is another name for the `LabelOneComponent` algorithm?
2. How many times does `CountAndLabel` execute Line #1?
3. How many times does `CountAndLabel` execute Line #2?
4. What is the running time of `CountAndLabel`?
## Borůvka's Algorithm
```{javascript, eval=FALSE}
Borůvka(V, E): AddAllSafeEdges(E, F, count):
F = (V, ∅) for i <- 1 to count
count <- CountAndLabel(F) safe[i] <- Null
while count > 1 for each edge uv ∈ E
AddAllSafeEdges(E, F, count) if comp(u) != comp(v)
count <- CountAndLabel(F) if safe[comp(u)] = Null or w(uv) < w(safe[comp(u)])
return F safe[comp(u)] <- uv
if safe[comp(v)] = Null or w(uv) < w(safe[comp(v)])
safe[comp(v)] <- uv
for i <- 1 to count
add safe[i] to F
```
## Borůvka's Algorithm
```{javascript, eval=FALSE}
Borůvka(V, E): AddAllSafeEdges(E, F, count):
F = (V, ∅) for i <- 1 to count
count <- CountAndLabel(F) safe[i] <- Null
while count > 1 for each edge uv ∈ E
AddAllSafeEdges(E, F, count) if comp(u) != comp(v)
count <- CountAndLabel(F) if safe[comp(u)] = Null or w(uv) < w(safe[comp(u)])
return F safe[comp(u)] <- uv
if safe[comp(v)] = Null or w(uv) < w(safe[comp(v)])
safe[comp(v)] <- uv
for i <- 1 to count
add safe[i] to F
```
5. What is the running time of the *first* `CountAndLabel` call?
6. After the *first* `AddAllSafeEdges` call, how many components (at most) are there? (i.e., what is the maximum possible value of `count`?)
7. What is the worst-case number of iterations of the `while`-loop?
8. What is the running time of subsequent `CountAndLabel` calls?
9. Give an upper bound on the running time of `AddAllSafeEdges`.
## Bonus Reading
Read pp. 262-263. *Upshot:* Borůvka's Algorithm often beats its worst-case $O(E \log V)$ running time.
# Classical MST Algorithms
# Announcement: CS Candidate
## Invitation for Feedback
Dr. Wonjun Lee will be interviewing next week for our open CS professor position.
- **Colloquium:** MG Tent #1: 3:30-5pm, Tuesday, March 30 (location tentative).
- **Teaching Demo:** Monday, March 29, 9:10-10:15: https://youtu.be/IFvpuv5k_ZU
I have to attend the Teaching Demo, so **class is cancelled for Monday, 3/29.** (Also office hours will end early on Tuesday.)
- Please consider **attending Tuesday's colloquium** as a substitute.
# Assignment Comments, Sample Solutions
## One pass: High level description
(See Jamboard)
- Mark the edges to contract (find min, should be $O(E)$).
- For each marked edge $uv$:
- Make a new vertex/linked list $n$
- Add all of $u$'s neighbors to $n$, and weight them appropriately.
- Add all of $v$'s neighbors to $n$, and weight them. (avoiding duplicates somehow)
- Add $n$ to the linked lists of the vertices in $n$'s list.
- Remove $u$ and $v$'s lists.
Need to add some details to this to specify completely. $O(V+E)$?
## Partial solution? Could we speed it up?
```
Boruvka(G) {
initalize set edges_to_collapse
for each vertex v in G {
min_edge = null
min_weight = infinity
for each edge uv according to the adjacency list {
if uv.weight < min_weight {
min_edge = uv
min_weight = uv.weight
}
}
add min_edge to edges_to_collapse
}
for each edge uv in edges_to_collapse {
add new node x to adjacency list
for each neighbor n of u
add n to x's linked list
change "u" in n's linked list to "x"
for each neighbor n of v
if n is already in x's linked list
if nv.weight > nu.weight
nx.weight = nv.weight
else
add n to x's linked list
change "v" in n's linked list to "x"
remove u and v nodes from adjacency list
}
}
```
## Another nice try
```
BoruvkaContraction(A[1..V]):
//iterate over all edges and mark those to be contracted
for i <- 1..V:
edges <- A[i] //has indices 1..n
min <- (edge with weight of infinity)
for j <- 1..n:
if edges[j].weight < min.weight:
min <- the edge from i to edges[j]
mark the edge min
for i <- 1..V:
if A[i] contains a marked edge uv:
//add v's out-edges to u
new <- A[u]
old <- A[v]
for j <- 1..n:
if old[j] is not in new:
add old to A[u] // new
else: //only add smallest parallel edge
parallel <- from new to old[j]
if old[j].weight < parallel.weight:
delete parallel from A[u] // new
add A[v][j] to A[u]
replace v in A[old[j]] with u
delete old
```
# Classical MST Algorithms
## Prim's Theorem; Meta-algorithm
**Theorem.** Let $F$ be an intermediate spanning forest of a weighted graph $G$, and suppose $e$ is a safe edge. Then the minimum spanning tree contains $e$.
```{javascript, eval=FALSE}
MetaMST(V,E)
F = (V, ∅)
while F is not a tree
add a safe edge to F // NOTE: This choice needs to be specified!!
return F
```
## Jarník's Algorithm (aka Prim's algorithm)
- Start with any vertex $T$.
- Add $T$'s safe edge to $T$.
- Repeat until you run out of vertices.
Exercise: Describe this completely, and verify its running time.
## Kruskal's Algorithm
- Start with the forest $F$ of vertices.
- Scan all edges by increasing weight; if an edge is safe, add it to $F$.
```
Kruskal(V, E):
sort E by increasing weight (e.g., MergeSort)
F <- (V, ∅)
for each vertex v ∈ V
MakeSet(v) // Set data structure partitioning V
for i <- 1 to |E|
uv <- ith lightest edge in E
if Find(u) != Find(v) // Are u and v in different partitions?
Union(u, v)
add uv to F
return F
```
- Need $O(E \log E)$ to sort, and that's the most expensive step.
- In general, $E$ is going to be bigger than $V$ for connected graphs, but at most $E = O(V^2)$. So $\Theta(\log E) = \Theta(\log V)$.
- So the time is $O(E \log V)$ (which is the same as $O(E \log E)$, in this case).
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(3262021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Step through Jarník and Kruskal
1. On the Jamboard, step through Jarník's algorithm on the given graph. Label the edges in the order they get added. Start at the vertex at the top.
2. On the Jamboard, step through Kruskal's algorithm on the given graph. Label the edges in the order they get added.
# Adjacency Matrices
## Recall: Adjacency Matrix
Weighted graphs can be represented with $V \times V$ *matrix*:
$$
\begin{bmatrix}
a_{1,1} & a_{1,2} & \cdots & a_{1,V} \\
a_{2,1} & a_{2,2} & \cdots & a_{2,V} \\
\vdots & \vdots && \vdots \\
a_{V,1} & a_{V,2} & \cdots & a_{V,V}
\end{bmatrix}
$$
- $a_{i,j} = w$ if there is an edge from vertex $i$ to vertex $j$ of weight $w$.
- $a_{i,j} = 0$ if there isn't an edge.
- More efficient for *dense* graphs (lots of edges). Less efficient for *sparse* graphs.
## Compute the adjacency matrix
3. Compute the adjacency matrix for the graph given on the Jamboard.
# Single Source Shortest Path Algorithms
# Assignment Comments
## Jarník Example
Order of addition: KH KJ JI IF FC FG FE GD DB DA

## Jarník Description and Time
Use a priority queue that does `DecreaseKey`, `Insert`, and `ExtractMin` each in $O(\log V)$ time.
```
Jarník(G):
pick random vertex v
T <- graph containing just v
Insert all neighboring edges into priority queue (key = weight)
while the priority queue is not empty:
ExtractMin edge uv
if uv is unmarked and u and v are not both in T:
mark uv
add uv to T
for each unmarked edge neighboring u and v
Insert edge (key = weight)
```
- Each edge gets marked once, so there are $O(E)$ `ExtractMin` and `Insert`'s.
- Time $O(E \log E)$.
- Recall that $O(E \log E) = O(E \log V)$ since $E \in O(V^2)$.
## Another Jarník Description
```
JarnikTree(G, start_vertex):
tree = Tree()
active_edges = PriorityQueue()
add G[start_vertex].edges to active_edges (sorted by edge weight)
while tree.node_count != G.node_count:
safe = pop from active_edges
if G[safe] in tree: continue
add G[safe] to tree
add G[safe].edges to active_edges (sorted by edge weight)
return tree
```
- See also Figure 7.5 (and just use a binary heap)
## Adjacency Matrix Example
```
A B C D E F G H I J K
A 0 7 0 3.2 0 0 0 0 0 0 0
B 7 0 8.9 3 0 0 0 0 0 0 0
C 0 8.9 0 9 6 2 0 0 0 0 0
D 3.2 3 9 0 0 5 4.1 0 0 0 0
E 0 0 6 0 0 4 0 5.7 0 0 0
F 0 0 2 5 4 0 2.6 0 3.7 0 0
G 0 0 0 4.1 0 2.6 0 0 0 7.5 0
H 0 0 0 0 5.7 0 0 0 8 0 4.7
I 0 0 0 0 0 3.7 0 8 0 1 6.2
J 0 0 0 0 0 0 7.5 0 1 0 5.3
K 0 0 0 0 0 0 0 4.7 6.2 5.3 0
```
## Adjacency Matrix Jarník description/time
```
// s is starting vertex
// M is adjancency matrix
Jarnik(M[V,V],s):
T <-({s},∅)
neighbors <- []
neighbors.add(s)
while neighbors is not empty
for each e ∈ neighbors
min <- infinity
for i <- 1 to |V|
if M[e,i] != 0 and M[e,i] < min
min <- M[e,i]
newNeighbor <- i
add newNeighbor to T
neighbors.add(newNeighbor)
return T
```
Time: $O(V^3)$
# Shortest Paths
## Shortest Paths, SSSP
- Now we consider **directed**, **weighted** graphs with *positive* weights.
- The natural problem is how to get from one vertex to another following the directed path of least weight.
- e.g., transportation optimization, network routing, LaTeX line breaking, Rubik's Cube, etc.
- Finding the shortest path from $s$ to $f$ usually means we have to find the shortest path from $s$ to everything.
- Find the **SSSP Tree.**
- Similar to Breadth-First spanning tree, but with weights.
## Tentative Shortest Paths and Predecessors
- $s$ is the start vertex.
- $s \rightsquigarrow v$ is the **tentative shortest path** from $s$ to $v$.
- $\text{dist}(v)$ is the **weight** of the tentative shortest path $s \rightsquigarrow v$.
- $\text{pred}(v)$ is the **predecessor** of $v$ in $s \rightsquigarrow v$.
We find the shortest path by updating the tentative shortest paths until we can't make them any better.
## Tense edges
- $\text{dist}(v)$ is the *weight* of the tentative shortest path $s \rightsquigarrow v$.
- $\text{pred}(v)$ is the *predecessor* of $v$ in $s \rightsquigarrow v$.
An edge $u\rightarrow v$ is called **tense** if $\text{dist}(u) + w(u\rightarrow v) < \text{dist}(v)$.
- So we can improve things by going through $u\rightarrow v$. (**relax**ing)
- That is, replace the tentative $s \rightsquigarrow v$ with $s \rightsquigarrow u \rightarrow v$, and update $\text{dist}(v)$ and $\text{pred}(v)$.
## SSSP by Repeated Relaxing: Meta-Algorithm
```
InitSSSP(s): Relax(uv):
dist(s) <- 0 dist(v) <- dist(u) + w(uv)
pred(s) <- Null pred(v) <- u
for all vertices v != s
dist(v) <- Infinity
pred(v) ← Null
MetaSSSP(s):
InitSSSP(s)
while there is at least one tense edge // NOTE: need to specify how to check
Relax any tense edge // NOTE: need to specify how to choose
```
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(3302021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Find the SSSP Tree: Jamboard
Starting at the leftmost vertex $s$, apply repeated `Relax`ings to produce the SSSP tree for the given graph. Make note of a relaxing that you do where none of the distances are $\infty$.
# Variations
## Dijkstra's Algorithm
Use a priority queue that does `DecreaseKey`, `Insert`, and `ExtractMin` each in $O(V)$ time.
- The vertices go in the priority queue.
- The key for vertex $v$ is $\text{dist}(v)$.
- Starting with $s$, process the smallest edge and loop.
```
DijkstraSSSP(s):
InitSSSP(s)
for all vertices v
Insert(v, dist(v))
while the priority queue is not empty
u <- ExtractMin()
for all edges uv
if uv is tense
Relax(uv)
DecreaseKey(v, dist(v))
```
(See Figure 8.12)
## Jamboard
Step through `DijkstraSSSP` on the Jamboard. Keep track of each `Relax` call (which edge gets relaxed, and in which order).
## Dijkstra running time
```
DijkstraSSSP(s):
InitSSSP(s)
for all vertices v
Insert(v, dist(v))
while the priority queue is not empty
u <- ExtractMin()
for all edges uv
if uv is tense
Relax(uv)
DecreaseKey(v, dist(v))
```
- `DecreaseKey`, `Insert`, and `ExtractMin` are all $O(\log V)$.
- At most $E$ `DecreaseKey`, at most $V$ `Insert`, and `ExtractMin`.
- Graphs are connected, so $E$ is "bigger" than $V$.
- Total time: $O(E \log V)$
## Bellman-Ford
- Relax *all* the tense edges, and recurse.
- Use an array `dist[]` to store the distances for each vertex.
```
BellmanFordSSSP(s)
dist[s] <- 0
for every vertex v != s
dist[v] <- Infinity
for i <- 1 to V − 1
for every edge uv
if dist[v] > dist[u] + w(uv)
dist[v] <- dist[u] + w(uv)
```
Time: $O(VE)$
# SSSP Trees, continued
# Assignment Comments
## Single Source Shortest Path
```
InitSSSP(s): Relax(uv):
dist(s) <- 0 dist(v) <- dist(u) + w(uv)
pred(s) <- Null pred(v) <- u
for all vertices v != s
dist(v) <- Infinity
pred(v) ← Null
MetaSSSP(s):
InitSSSP(s)
while there is at least one tense edge // NOTE: need to specify how to check
Relax any tense edge // NOTE: need to specify how to choose
```
## Dijkstra's Algorithm
```
DijkstraSSSP(s):
InitSSSP(s)
for all vertices v
Insert(v, dist(v))
while the priority queue is not empty
u <- ExtractMin()
for all edges uv
if uv is tense
Relax(uv)
DecreaseKey(v, dist(v))
```
## Step Through Dijkstra's Algorithm
Relaxation order: 2.0, 4.5, 4.7, 6.4, 5.9, 5.5, 3.6, 5.1, 3.4, 4.8, 1.1, 5.4, 3.7

## Looped Trees
- Every leaf has an edge back to the root.
- Otherwise, $G$ is a binary tree with $n$ vertices and $n-1$ edges.
- There are about $n/2 = \Theta(n)$ leaves.
- So there are $n-1 + \Theta(n) = O(n)$ edges in the looped tree.
- Dijkstra Time: $O(E \log V) = O(n \log n)$.
## Faster shortest path algorithm
- If $u$ is above $v$, then BFS (starting at $u$) will find the (only) path in $O(n)$ time.
- If $v$ is above $u$, the the shortest path will be the shortest path from $u$ to the root, followed by the only path from the root to $v$.
- Consider the reversal graph ($O(n)$).
- BFS, starting at root. Mark each node with a `distanceFromRoot` attribute.
- If new distance is less than marked distance, update, and update parents.
- $O(n)$, because each node is only ever going to be marked twice.
# Shortest Paths
## Tentative Shortest Paths and Predecessors
- $s$ is the start vertex.
- $s \rightsquigarrow v$ is the **tentative shortest path** from $s$ to $v$.
- $\text{dist}(v)$ is the **weight** of the tentative shortest path $s \rightsquigarrow v$.
- $\text{pred}(v)$ is the **predecessor** of $v$ in $s \rightsquigarrow v$.
- $\text{dist}(v)$ is the *weight* of the tentative shortest path $s \rightsquigarrow v$.
- $\text{pred}(v)$ is the *predecessor* of $v$ in $s \rightsquigarrow v$.
An edge $u\rightarrow v$ is called **tense** if $\text{dist}(u) + w(u\rightarrow v) < \text{dist}(v)$.
## SSSP by Repeated Relaxing: Meta-Algorithm
```
InitSSSP(s): Relax(uv):
dist(s) <- 0 dist(v) <- dist(u) + w(uv)
pred(s) <- Null pred(v) <- u
for all vertices v != s
dist(v) <- Infinity
pred(v) ← Null
MetaSSSP(s):
InitSSSP(s)
while there is at least one tense edge // NOTE: need to specify how to check
Relax any tense edge // NOTE: need to specify how to choose
```
- `pred(v)` and `dist(v)` get updated as the algorithm `metaSSSP` runs.
- So edges that were tense become not tense.
- **Correctness:** We need to prove that, if there are no tense edges, then the *tentative shortest path* $s \rightarrow \cdots \rightarrow \text{pred}(\text{pred}(v)) \rightarrow \text{pred}(v) \rightarrow v$ is in fact a shortest path from $s$ to $v$.
## Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Josiah", "Nathan")
set.seed(462021)
n <- length(roster)
ngps <- 7
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Predecessor paths
1. Suppose that $s = \text{pred}(v) = \text{pred}(u)$, but the path $s \rightarrow v$ is longer than the path $s \rightarrow u \rightarrow v$. Which edge is tense?
2. Suppose that $s \rightarrow \cdots \rightarrow \text{pred}(\text{pred}(v)) \rightarrow \text{pred}(v) \rightarrow v$ is not a shortest path from $s$ to $v$. That is, suppose there is a shorter path $s \rightarrow u_1 \rightarrow u_2 \rightarrow \cdots \rightarrow u_k \rightarrow v$.
a. Explain why you can relax the edges in order $su_1, u_1u2, \ldots, u_{k-1}u_k$.
b. Once you have done that, which edge is tense?
# Shortest paths in DAGs
## Recall: DAGs
- A directed graph *without cycles* is called a **directed acyclic graph** (DAG).
- A *topological ordering* of $G$ is an ordering $\prec$ of the vertices such that $u \prec v$ for every edge $u \rightarrow v$.
- In other words, it is a listing of the vertices that respects the arrows.
```
TopologicalSort(G):
Call DFSAll(G) to compute finishing times v.post for all v in G
Return vertices in order of decreasing finishing times
```
So we can topologically sort the vertices in $O(V+E)$ time.
## Shortest Paths in DAGs
Recursive Structure: Compute the length of the shortest path from $s$ to $v$.
```
LengthSP(v):
if v = s