Graph Algorithms

29
1 Graph Algorithms Minimum Spanning Trees (MST) Union - Find Dana Shapira םםםם םםםםםם םם םםםם םםםםםם. םם םםםםםם םםםם םם םםםםםםם םםםםםםם, םםם םםםםם םם םם םםםם3/7/200 7

description

3/7/2007. נדבר השיעור על עצים פורשים. כל הגרפים יהיו לא מכוונים וקשירים, לכן בהכרח יש עץ פורש. Graph Algorithms. Minimum Spanning Trees (MST) Union - Find Dana Shapira. Spanning tree. עץ פורש- מכיל את כל הקודקודים של הגרף, אבל לא בהכרח את כל צלעותיו (אין בו צלעות הסוגרות מעגל). - PowerPoint PPT Presentation

Transcript of Graph Algorithms

Page 1: Graph Algorithms

1

Graph Algorithms

Minimum Spanning Trees (MST)Union - Find

Dana Shapira

נדבר השיעור על עצים פורשים.

כל הגרפים יהיו לא מכוונים וקשירים, לכן בהכרח יש עץ פורש

3/7/2007

Page 2: Graph Algorithms

2

A spanning tree of G is a subset T E of edges, such that the sub-graph G'=(V,T) is connected and acyclic.

Spanning treeעץ פורש-

מכיל את כל הקודקודים של הגרף, אבל לא בהכרח את כל צלעותיו (אין בו צלעות

הסוגרות מעגל).

Page 3: Graph Algorithms

3

Minimum Spanning Tree

Given a graph G = (V, E) and an assignment of weights w(e) to the edges of G, a minimum spanning tree T of G is a spanning tree with minimum total edge weight

5

4

3

3

6

1

6

9

8

3

71

2

7

עץ פורש מינימלי-

הוא עץ פורש שסכום המשקולות על הצלעות שלו הוא מינימלי

)MST(

Page 4: Graph Algorithms

4

How To Build A Minimum Spanning Tree

General strategy:1. Maintain a set of edges A such that (V, A) is a spanning

forest of G and such that there exists a MST (V, F) of G such that AF.

2. As long as (V, A) is not a tree, find an edge that can be added to A while maintaining the above property.

Generic-MST(G=(V,E))1. A= ;2. while (A is not a spanning tree of G) do3. choose a safe edge e=(u,v)E4. A=A{e}5. return A

כדי למצוא עץ פורש מינימלי, נתחיל בבחירת הקשת שהכי טובה לנו.

, שהיא מוכלת בקב' של הקשתות G את קבוצת הקשתות של Aנסמן ב-של העץ הפורש המינימלי. נוסיף לה כל הזמן קשתות עד שנגיע לעץ

הפורש המינימלי.

- קשת ששייכת לעץ הפורש המינימלי ואפשר לצרף קשתות בטוחותאנחנו מחפשים Aאותה ל-

- קשת עם משקל מינימלי מבין קשתות המקיימות תכונה קשת קלהנקרא לקשת כזו כלשהי שנראה בהמשך

Page 5: Graph Algorithms

5

Cuts

A cut (X, Y) of a graph G = (V, E) is a partition of the vertex set V into two sets X and Y = V \ X.

An edge (v, w) is said to cross the cut (X, Y) if v X and w Y.

A cut (X, Y) respects a set A of edges if no edge in A crosses the cut.

קבוצות זרות ומשלימות.2- חלוקה של קודקודים ל- cut(x,y)חתך

אם קודקוד אחד שייך לקבוצה אחת והקודקוד קשת חוצה את החתךהשני לקבוצה השנייה (באיור אלו הקשתות הכחולות).

אם אין בה קשתות חותכות מכבדת את החתךAקבוצה

Page 6: Graph Algorithms

6

Theorem: Let A be a subset of the edges of some minimum spanning tree of G; let (X, Y) be a cut that respects A; and let e be a minimum weight edge that crosses(X, Y). Then A {e} is also a subset of the edges of a minimum spanning tree of G; edge e is safe.

A Cut Theorem

1

49

3

2

4

A Cut Theorem

מכבדת את A) Aנגדיר תת קבוצה של העץ הפורש, את קשתות: נסתכל על כל הקשתות Aהחתך). נוסיף ל-

החוצות את החתך ומתוכן ניקח את הקשת עם המשקל (זוהי הקשת הבטוחה).Aהמינימלי ואותה נוסיף ל-

עדיין תהייה תת קבוצה של העץ הפורש. Aנשים לב ש-ונוכיח זאת.

הוכחה אינטואטיבית-(הוכחה פורמלית בהמשך המצגת)

A היא הקבוצה עם הקשתות האדומות וניתן לראות כי היא מכבדת את החתך הירוק.

נסתכל על כל הקשתות הכחולות שחוצות את החתך. מתוכן ניקח .Aאת הקשת עם המשקל הנמוך ביותר ונוסיף אותה ל-

נמשיך כך עבור החתכים השונים ונפסיק את התהליך כשאנחנו מגיעים לעץ פורש של כל הגרף.

נטען שעץ זה שהגענו אליו הוא הגרף הפורש המינימלי.

נמצאת e. אם הקשת המינימלית שנסמנה G ועל Aנסתכל על Pבעץ הפותר, אז סיימנו את ההוכחה. אחרת, יש מסלול אחר

f. כאשר fשסוגר מעגל יחד עם הצלע המינימלית, באמצעות צלע מכבדת את החתך.A כיון ש-Aאינה ב-

שתסגור את זה e ונוסיף את fנבנה עץ פורש אחר בו נוריד את .T במקום העץ הקודם ’Tלעץ חדש-

T’ .יהיה העץ הפורש המינימלי

Page 7: Graph Algorithms

7

49

12

Theorem: Let A be a subset of the edges of some minimum spanning tree of G; let (X, Y) be a cut that respects A; and let e be a minimum weight edge that crosses(X, Y). Then A {e} is also a subset of the edges of a minimum spanning tree of G; edge e is safe.

A Cut Theorem

Page 8: Graph Algorithms

8

e

A Cut Theorem

e

f

T w(e) ≤ w(f)w(e) ≤ w(f)

w(T') ≤ w(T)

u

v

Page 9: Graph Algorithms

9

Let T be a MST such that AT. If e = (u,v) T, add e to T. The edge e = (u,v) forms a cycle with edges on the path p from u

to v in T. Since u and v are on opposite sides of the cut, there is at least one edge f = (x,y) in T on the path p that also crosses the cut.

f A since the cut respects A. Since f is on the unique path from u to v in T, removing it breaks T into two components.

w(e) ≤ w(f) (why?) Let T ' = T – {f} {e} w(T ') ≤ w(T).

Proof:

Page 10: Graph Algorithms

10

Proof: The cut (VC, V–VC) respects A, and e is a light edge for this cut. Therefore, e is safe.

Corollary: Let G=(V,E) be a connected undirected graph and A a subset of E included in a minimum spanning tree T for G, and let C=(VC,EC) be a tree in the forest GA=(V,A). If e is a light edge connecting C to some other component in GA, then e is safe for A.

A Cut Theorem

Page 11: Graph Algorithms

11

Kruskal’s Algorithm

Kruskal(G)1 A ← ∅2 for every edge e = (v, w) of G, sorted by weight3 do if v and w belong to different connected components of (V, A)4 then add edge e to A

(a, d):1 (h, i):1 (c, e):1 (f, h):2 (g, h):2(b, c):3 (b, f):3 (b, e):4 (c, d):5 (f, g):5(e, i):6 (d, g):8 (a, b):9 (c, f):12

2

1

112 8

5

3

9

4

3

25

1

6

a

bc

d

e

f

gi

h2

1

112 8

5

3

9

4

3

25

1

6

a

bc

d

e

f

gi

h

? Aאיך בוחרים את החתך שמכבד את . C ונסמנו Aנסתכל על רכיב קשיר שנמצא ב-

וכך Aנחבר בין תת העץ הקשיר הזה לרכיב קשירות אחר של . e. החיבור יעשה באמצעות Aנגדיל את

מכבדת את החתך. לכן: חתך שמפריד A נרצה לראות ש- לבין שאר הקשתות, יהיה חתך המכבד Cבין קבוצת הקשתות של

. לכן A קשת קלה של החתך. והחתך מכבד את A. eאת e-קשת בטוחה שניתן להוסיף אותה ל A-כך ש A עדיין תהייה תת

קבוצה שמוכלת- שווה לעץ הפורש המינימלי. ובכך סיימנו את הוכחת המשפט. בצעד הראשון לוקחים את

=קב' ריקה בהתחלה)Aהקשת הקלה ביותר (כי

האלגוריתם הבא מראה את הדברים (כאשר כל קודקוד הוא רכיב קשירות בפני עצמו)

Page 12: Graph Algorithms

12

Correctness Proof

ei

ei

Sorted edge sequence: e1, e

2, e

3, e

4, e

5, e

6, …, e

i, e

i + 1, e

i + 2, e

i + 3, …, e

n

Every edge ej that cross the cut have a weight w(e

j) ≥ w(e

i).

Hence, edge ei is safe.

Page 13: Graph Algorithms

13

Union-Find Data Structures

Given a set S of n elements, maintain a partition of S into subsets S

1, S

2, …, S

k

Support the following operations:Union(x, y): Replace sets S

i and S

j such that x S

i and y S

j

with Si S

j in the current partition

Find(x): Returns a member r(Si) of the set S

i that contains x

In particular, Find(x) and Find(y) return the same element if and only if x and y belong to the same set.It is possible to create a data structure that supports the above operations in O(α(n)) amortized time, where α is the inverse Ackermann function.

תחזיר α(n)הערכים מאוד מאוד קטנים לכן 5מקסימום

קודקודים שייכים לאותו רכיב 2כדי לדעת אם union-findקשירות, נעזר במבנה הנתונים

Page 14: Graph Algorithms

14

Kruskal’s Algorithm Using Union-Find Data Structure

Kruskal(G,w)A for each vertex vV do

Make-Set(v)sort the edges in E in non-decreasing weight order wfor each edge (u,v)E do

if Find-Set(u) ≠ Find-Set(v) then A A {(u,v)}

Union(u,v) return A

Page 15: Graph Algorithms

15

Kruskal’s Algorithm Using Union-Find Data Structure

Analysis:O(|E| log |E|) time for everything except the operations on SCost of operations on S:

O(α(|E|,|V|)) amortized time per operation on S|V| – 1 Union operations|E| Find operationsTotal: O((|V| + |E|)α(|E|,|V|)) running time

Total running time: O(|E| lg |E|).

בהנחה שאנו יודעים לממש את האלגוריתם, מהו זמן הריצה שלו?

זמן מינימלי למיון קשתות

סה"כ לאחר מיון הקשתות לא

כולל מתנהגת αכיון ש-

כמעט כמו קבוע נקבל שבסה"כ:

Page 16: Graph Algorithms

16

Union/Find

Assumptions: The Sets are disjoint. Each set is identified by a representative of the set.

Initial state: A union/find structure begins with n elements, each considered

to be a one element set. Functions:

Make-Set(x): Creates a new set with element x in it. Union(x,y): Make one set out of the sets containing x and y. Find-Set(x): Returns a pointer to the representative of the set

containing x.

נסתכל על הפעולות על מבנה הנתונים ונבין מה זמן הריצה שלהן

תומך בפעולות

מחזירים נציג של הקבוצה

Page 17: Graph Algorithms

17

Basic Notation

The elements in the structure will be numbered 0 to n-1 Each set will be referred to by the number of one of the

element it contains Initially we have sets S0,S1,…,Sn-1

If we were to call Union(S2,S4), these sets would be removed from the list, and the new set would now be called either S2 or S4

Notations: n Make-Set operations m total operations nm

נמספר את האיברים

נסמן

עברנו לקבוצות כי הרעיון הזה עוזר לפתור עוד בעיות מלבד זו שראינו בשיעור הקודם

Page 18: Graph Algorithms

18

First Attempt

Represent the Union/Find structure as an array arr of n elements

arr[i] contains the set number of element i Initially, arr[i]=i (Make-Set(i))

Find-Set(i) just returns the value of arr[i] To perform Union(Si,Sj):

For every k such that arr[k]=j, set arr[k]=i

נסיון ראשון לביצוע הפעולות בכמה שפחות זמן

O(1)פעולה אחת-

נעזר במערך nשיכיל את

האיברים

בהתחלה כל איבר עומד בפני עצמו,

מכיל arr[i]ולכן את האיבר עצמו.

בהתחלה כל איבר נמצא בקבוצה

שמכילה רק אותו. אם הוא שייך

הוא יהיה ב- Siל-arr[j].

Union- O(n) כיון שעוברים על כל – המערך

Page 19: Graph Algorithms

19

Analysis

The worst-case analysis: Find(i) takes O(1) time Union(Si,Sj) takes (n) time

A sequence of n Unions will take (n2) time

מה יהיה זמן הריצה במצב זה?

עוברים על כל איברי המערך

לוקחים סדרה כדי לקבל סיבוכיות לשיעורין

Page 20: Graph Algorithms

20

Second Attempt

Represent the Union/Find structure using linked lists. Each element points to another element of the set. The representative is the first element of the set. Each element points to the representative. How do we perform Union(Si,Sj)?

נסיון שני, ננסה שלא להשתמש במשהו שלוקח O(n).

נעזר ברשימה מקושרת.

כל איבר מצביע לבא בתור וגם לאיבר הראשון ברשימה, שהוא יהיה המייצג של הקבוצה.

נניח שיש מצביע לאיבר הראשון ברשימה ולאיבר האחרון ברשימה.

, נוסיף רשימה אחת לסופה של האחרת. ונדאג שכל האיברים ברשימה האחרת יצביעו unionכדי לבצע לאיבר הראשון (המייצג של הרשימה) החדש.

.O(1) בזמן של findיהיה מערך שמצביע לכל האיברים, ככה יהיה ניתן לעשות

Find לאיבר שאנחנו רוצים, מוביל לתא שלו במערך, שמוביל אליו, שמוביל לאיבר הראש הרשימה (לנציג הרשימה).

Page 21: Graph Algorithms

21

Analysis

The worst-case analysis: Find(i) takes O(1) time Make-Set(i) takes O(1) time Union(Si,Sj) takes (n) time (Why?)

A sequence of n Unions-Find will take (n2) time (Example?)

מה יהיה זמן הריצה במצב זה?

n/2כי צריך לעבור בממוצע על איברים

פעולות.nעשינו

Make-set עכשיו O(n) פעולות שלוקחות סה"כ Θ(n2) של union-find.

union(x2,x1) נבצע את פעולות האיחוד עד הסוף:

union(x3,x2) n-1

פעולות …

union(xn,xn-1)

זמן הריצה לשיעורין: n*O(1) + (n-1) Θ(n) =( O(n) + O(n2) ) / 2 = Θ(n2)

unionMake-setנחלק במס' הפעולות

Page 22: Graph Algorithms

22

Up-Trees A simple data structure for implementing disjoint sets is the up-

tree. We visualize each element as a node A set will be visualized as a directed tree

Arrows will point from child to parent The set will be referred to by its root

A

H

W

H, A and W belong to the same set. H is the representative

B

X

R

F

X, B, R and F are in the same set. X is the representative

מבנה נתונים נוסף שאולי יעזור לנו כי עדיין לא השגנו זמן עץ שבו כל שורש הוא הנציג של הקבוצהריצה טוב הוא

Page 23: Graph Algorithms

23

Operations in Up-Trees

Follow pointer to representative element.

find(x) {

if (x≠p(x)) // not the representative

then p(x)find(p(x));return p(x);

}

נראה את הפעולות על העץ

P(x) האב של -x

Page 24: Graph Algorithms

24

Union

Union is more complicated.

Make one representative element point to the other, but which way?Does it matter?

Page 25: Graph Algorithms

25

Union(H, X)

A

H

W B

X

R

F

A

H

W B

X

R

F

X points to H

B, R and F are now deeper

H points to X

A and W are now deeper

דוגמא:

עדיף שאיברי הקבוצה הקטנה יצביעו כולם לראש של הקבוצה הגדולה.

.findזה יעסוק בזמן הריצה של

Page 26: Graph Algorithms

26

A worst case for Union

Union can be done in O(1), but may cause find to become O(n)

A B C D E

Consider the result of the following sequence of operations:

Union (A, B)Union (C, A)Union (D, C)Union (E, D)

נקבל עץ מנוון:

וזה לא עזר לנו לגבי זמן הריצהA

B

C

D

E

Page 27: Graph Algorithms

27

Array Representation of Up-tree

Assume each element is associated with an integer i=0…n-1. From now on, we deal only with i.

Create an integer array, A[n] An array entry is the element’s parent A -1 entry signifies that element i is the representative element.

נבחן ייצוג של עץ הפוך באמצעות מערך

כל איבר נמצא במקום שלו. במקום של הנציג נשים -1.

Page 28: Graph Algorithms

28

Array Representation of Up-tree

Now the union algorithm might be:Union(x,y) {

A[y] = x; // attaches y to x}

The find algorithm would befind(x) {

if (A[x] < 0)return(x);

elsereturn(find(A[x]));

}Performance: ???

איך מתבצעות הפעולות בייצוג הזה?

הגענו לשורש

נחפש את מי שנמצא באותו

מקום במערך (בתא שמור האינדקס של

האבא)

דוגמא למימוש יש בהמשך

Page 29: Graph Algorithms

29

Analysis

Worst case: Union(Si,Sj) take O(1) time Find(i) takes O(n) time

Can we do better in an amortized analysis? What is the maximum amount of time n operations could

take us? Suppose we perform n/2 unions followed by n/2 finds

The n/2 unions could give us one tree of height n/2-1 Thus the total time would be n/2 + (n/2)(n/2) = O(n2)

This strategy doesn’t really help…

מה יהיה זמן הריצה במצב זה?

נשים לב שעדיין לא השגנו זמן ריצה טוב