Week05 Graph 1

Embed Size (px)

Citation preview

  • 7/28/2019 Week05 Graph 1

    1/69

    This course material is now made available for public usage.Special acknowledgement to School of Computing, National University of Singapore

    for allowing Steven to prepare and distribute these teaching materials.

    Com etitive Pro rammin

    Week 05 Graph 1 (Basics)

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    2/69

    Mini Contest #4 + Break + Discussion

    Admins CS2010/2020 Reviews (not discussed in details except red ones )

    Graph: Preliminary & Motivation rap raversa gor ms

    DFS/BFS: Connected Components /Flood Fill DFS only: Toposort/Cut Vertex+Bridges/ Strongly Connected Components

    Minimum Spanning Tree Algorithm

    Kruskals and Prims: Plus Various Applications

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    3/69

    CS2010 2020 Reviews (not discussed in details except red ones ) Single Source Shortest Paths

    Dijkstras: SSSP on Weighted (no ve cycle) graph/Variants

    AllPairs Shortest Paths

    Floyd Warshalls + Variants Special Graphs Part 1

    , ,

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    4/69

    Vertices Nodes

    Edges

    (Strongly) Connected Component

    Un/Weighted Un/Directed

    u rap Complete Graph

    In/Out Degree Self Loop/Multiple Edges

    recte

    cyc c

    rap Tree/Forest

    Multigraph vs Simple

    Graph

    Euler Hamiltonian

    Path/Cycle parse ense Path, Cycle

    par e rap

    so ate , eac a eCS3233 Competitive Programming,

    Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    5/69

    Kaohsiun 2006Standings & Felixs Analysis

    A. Print Wor s in LinesB. The Bug Sensor Problem

    A. DPB. Graph, MST

    . D. Lucky and Good MonthsE. Route Planning

    . D. Tedious Ad HocE. Search?

    Shift Cipher (N/A in Live Archive)F. A Scheduling Problem

    Complete Search + STLF. Greedy?

    . ec t e nesH. Perfect Service

    .H. DA Graph, DP on Tree

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    6/69

    Sin a ore 2007Standings & Felixs Analysis

    A. MODEXB. JONES

    A. Mat , Mo u o Arit meticB. DP

    .D. TUSKE. SKYLINE

    . D. GeometryE. DS, Segment Tree

    F. USHERG. RACING

    F. Graph, APSP, Min Weighted Cycle++G. Graph, Maximum Spanning Tree

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    7/69

    Jakarta 2008Standings & Suhendrys Analysis

    A. Anti Brute Force LocB. Bonus Treasure

    A. Grap , MSTB. Recursion

    . D. Disjoint PathsE. Expert Enough?

    .D. DA Graph, DP on TreeE. Complete Search (is enough)

    F. Free ParenthesesG. Greatest KPalindrome Sub

    F. DP, harder than problem IG. String

    . yper oI. ICPC Team Strategy

    . atI. DP, medium

    . . ,

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    8/69

    A. ASCII Diamon iB. Match Maker

    A. A HocB. DP, Stable Marriage Problem?

    . D. Irreducible FractionsE. Gun Fight

    . D. MathE. Graph, MCBM (AlternatingPath)

    F. Unlock the LockG. Ironman Race in Treeland

    F. Graph, SSSP (BFS)G. DA Graph, Likely DP on Tree?

    . oot ng t e onsterI. Addition Substraction Game

    . omp eoI. ?

    .

    K. Triangle Hazard.

    K. Math

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    9/69

    A. Sa esB. String Popping

    A. Brute ForceB. Recursive Backtracking

    .D. MinesE. Binary Search Tree

    . D. Geometry + SCCs (Graph)E. Graph, BST, Math, Combinatoric

    F. Tour BeltG. String Phone

    F. Graph, MST (modified)G. ?

    . nsta at onsI. Restaurant

    .I. ?

    . .

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    10/69

    Depth First Search (DFS)Breadth First Search (BFS)

    Reachability

    Flood FillTopological Sort

    Finding Cycles

    (Back

    Edges)

    Finding Articulation Points & Bridges

    GRAPH TRAVERSAL ALGORITHMS

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    11/69

    How to solve these UVa problems:

    469 Wetlands of Florida Similar problems: 260, 352, 572, 782, 784, 785, etc

    Similar problems: 1263, 11709, etc

    ou am ar y w ep rs earc

    algorithm and its variants, they look hard

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    12/69

    How to solve these UVa problems:

    336 A Node Too Far Similar problems: 383, 439, 532, 762, 10009, etc

    graph traversal algorithm , they look hard

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    13/69

    Given a graph, we want to traverse it!

    Depth First Search (DFS)

    sua y mp emen e us ng recurs on

    More natural ost requent y use to traverse a grap

    Breadth First Search (BFS) Usually implemented using queue (+ map), use STL Can solve special case* of shortest paths problem!

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    14/69

    O(V + E) if using Adjacency List

    O(V2) if using Adjacency Matrixt ypedef pai r i i ; t ypedef vect or vi ;

    voi d df s ( i nt u) { / / DFS f or nor mal usagepr i nt f ( " %d" , u) ; / / t hi s ver t ex i s vi si t eddf s_num[ u] = DFS_BLACK; / / mar k as vi s i t edf or ( i nt j = 0; j < ( i nt ) Adj Li s t [ u] . s i ze; j ++) {

    i i v = Adj Li s t [ u] [ j ] ; / / t r y al l nei ghbor s v of ver t ex ui f ( df s_ num[ v. f i r st ] == DFS_WHI TE) / / avoi d cycl e

    df s( v. f i r s t ) ; / / v i s a ( nei ghbor , wei ght ) pai r}

    }

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    15/69

    Complexity: also O(V + E) using Adjacency List

    map n , n s ; s sour ce = ;queue q; q. push( sour ce) ; / / st ar t f r om sour ce

    w e q. emp yi nt u = q. f r ont ( ) ; q. pop( ) ; / / queue: l ayer by l ayer !f or ( i nt j = 0; j < ( i nt ) Adj Li st [ u] . si ze( ) ; j ++) {

    v = s u ; or eac ne g our s o ui f ( ! di st . count ( v. f i r s t ) ) {

    di st [ v. f i r st ] = di st [ u] + 1; / / unvi si t ed + r eachabl eq. pus v. r s ; enqueue v. r s or nex s eps

    }}

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    16/69

    st

    DFS (and BFS) can find connected components

    A call of dfs u visits onl vertices connected to u

    i nt numComp = 0;

    df s_num . assi gn ( V, DFS_WHI TE) ;REP ( i , 0, V - 1) / / f or each ver t ex i i n [ 0. . V- 1]

    == _ _ pr i nt f ( " Component %d, vi si t " , ++numComp) ;

    df s( i ) ; / / one component f oundpr i nt f ( " \ n" ) ;

    }r i nt f ( " Ther e ar e %d connect ed com onent s\ n" , numCom ) ;

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    17/69

    n ng opo og ca or see ex ooFinding Articulation Points and Bridges (see text book)Findin Stron l Connected Com onent

    TARJANS DFS ALGORITHMS

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    18/69

    Tarjans SCC 0 DFSpann ng

    TreeInput: A Directed Graphdfs_num: visitation counter

    dfs_num(0) = 0 dfs_num(1) = 1 dfs_num(3) = 2 dfs_num(4) = 4 dfs_num(5) = 5

    s_ ow: owes s_num reac a e rom a ver exusing the current DFS spanning tree

    dfs_low(0) = 0 dfs_low(1) = 1 dfs_low(3) = 1 dfs_low(4) = 4 dfs_low(5) = 4

    1 30 4 5

    dfs_num(2) = 3dfs_low(2) = 1

    dfs_num(7) = 6dfs_low(7) = 4

    dfs_num(6) = 7dfs_low(6) = 4

    1320

    4576

    DAG aftercontracting

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    6SCCs

  • 7/28/2019 Week05 Graph 1

    19/69

    Code: Tarjans SCC (not in IOI syllabus)vi dfs_num, dfs_low, S, visited; / / gl obal var i abl es

    voi d t ar j anSCC( i nt u) {dfs_low[u] = dfs_num[u] = dfsNumberCounter++; / / df s_ l ow[ u]

  • 7/28/2019 Week05 Graph 1

    20/69

    DFS

    BFS

    Slightly easier to Can solve SSSP on

    Use less memory

    (discussed later)

    Cons:

    Cons: Slightly longer to

    unweighted graphs code

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    21/69

    Prims algorithm Read textbook on your own or revise CS2010 CS2020 material

    KRUSKALS ALGORITHM FOR MINIMUM SPANNING TREE

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    22/69

    Given this graph, select some edges s.t

    the ra h is connectedbut with minimal total weight!225

    MST!1 35

    58

    458

    5

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    23/69

    Given a connected undirected graph G,

    select E G such that a tree is formed and this tree spans (covers) all V G!

    There can be several spanning trees in G The one where total cost is minimum

    is called the Minimum Spanning Tree (MST) UVa: 908 (Reconnecting Computer Sites)

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    24/69

    pannng reeCost: 4+4+6+6 = 20

    nCost: 4+6+6+2 = 18

    e r g na rap

    124

    124

    124

    0 24

    68

    0 24

    68

    0 24

    68

    369

    369

    369

    4 4 4

  • 7/28/2019 Week05 Graph 1

    25/69

    Prims (Greedy Algorithm)

    At ever iteration choose an ed e withminimum cost that does not form a cycle

    rows an MST from a root

    Kruskals (also Greedy Algorithm) Repeate y in s e ges wit minimum costs

    that does not form a cycle forms an MST by connecting forests

    Which one is easier to code?CS3233 Competitive Programming,

    Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    26/69

    In my opinion, Kruskals algorithm is simplersor t edges by i ncr easi ng wei ght O( E l og E)while t her e ar e unpr ocessed edges l ef t O( E)

    pi ck an edge e wi t h mi ni mum costif addi n e t o MST does not f or m a c cl e

    add e t o MST

    (EdgeList) and sort them, or use Priority Queue

    es or cyc es us ng s o n e s n on n

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    27/69

    onnec anAs this edge is smallest

    onnec anNo cycle is formed

    e or g na grap ,no edge is selected

    124

    124

    124

    0 24

    68

    0 24

    68

    0 24

    68

    369

    369

    369

    4 4 4

    the MST formed. Observe that we can also choose toconnect vertex 2 and 0 also with weight 4!

  • 7/28/2019 Week05 Graph 1

    28/69

    onnec anMST is formed

    onnec an The next smallest edge

    anno connec anAs it will form a cycle

    124

    124

    124

    0 24

    68

    0 24

    68

    0 24

    68

    369

    369

    369

    444,

    determines how the MST formed; Connecting0 and 4 is also a valid next move

  • 7/28/2019 Week05 Graph 1

    29/69

    s s e naMST with cost 18

    owever, w nomodify anything else

    u s an ar rus a salgorithm will still continue

    124

    124

    124

    0 260 24

    68

    0 24

    68

    36369

    369

    444

  • 7/28/2019 Week05 Graph 1

    30/69

    sor t e y e ge costvect or < pai r > EdgeLi st ;

    / / i nser t edges i n f or mat ( wei ght , ( u, v) ) t o EdgeLi stsor t ( EdgeLi s t . begi n( ) , Edgel i s t . End( ) ;

    _

    f or ( i nt I = 0; I < E; i ++) { / / whi l e mor e edgespai r f r ont = EdgeLi s t [ i ] ;i f ( ! i sSameSet ( f r ont . second. f i r s t , f r ont . second. second) ) {

    / / i f addi ng e t o MST does not f or m a cycl emst cost += f r ont . f i r s t add t he wei ht of e t o MST _ uni onSet ( f r ont . second. f i r st , f r ont . second. second) ;

    }

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    31/69

    You have not teach us Union Find DS in CS3233??

    It is

    also

    only

    covered

    briefly

    in

    CS2010/CS2020

    Yeah, we choose to skip that DS in CS3233

    learn Union Find DS on your own (Sec 2.3.2) ,

    mini contests problems A + B

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    32/69

    BFS (unweighted)s ra s non ve cyc e

    Bellman Fords (may have ve cycle), not discussedFlo d Warshalls all airs

    SHORTEST PATHS

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    33/69

    SSSP is a classical problem in Graph theory:

    Find shortest aths from one source to the rest^ Special case: UVa 336 (A Node Too Far)

    Problem Description:

    Given an un weighted & un directed Graph,a starting vertex v , and an integer TTL

    or has distance > TTL from v

    . . _ ,

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    E l (1)0 1 2 3

  • 7/28/2019 Week05 Graph 1

    34/69

    Example (1)0 1 2 3

    4 765

    8 Q = {5}D[5] = 0

    9 10 11 12

    5

    0 1 2 3 E l (2)

  • 7/28/2019 Week05 Graph 1

    35/69

    0 1 2 3 Example (2)4 765

    8 Q = {5}Q = {1, 6, 10} D[5] = 0

    9 10 11 12= =

    D[6] = D[5] + 1 = 1D[10] = D[5] + 1 = 1

    1

    5 6

    10

    0 1 2 3 E l (3)

  • 7/28/2019 Week05 Graph 1

    36/69

    0 1 2 3 Example (3)4 765

    8 Q = {5}Q = {1, 6, 10} D[5] = 0

    9 10 11 12= , , ,

    Q = {10, 0, 2, 11 }Q = {0, 2, 11, 9}

    = =D[6] = D[5] + 1 = 1D[10] = D[5] + 1 = 1

    1 200 2

    D[2] = D[1] + 1 = 2D[11] = D[6] + 1 = 2

    = =

    5 6

    10 119

    0 1 2 3 Example (4)

  • 7/28/2019 Week05 Graph 1

    37/69

    0 1 2 3 Example (4)4 765

    8 Q = {5}Q = {1, 6, 10} D[5] = 0

    9 10 11 12= , , ,

    Q = {10, 0, 2, 11 }Q = {0, 2, 11, 9}

    = =D[6] = D[5] + 1 = 1D[10] = D[5] + 1 = 1

    1 20

    , , ,

    Q = {11, 9, 4, 3}Q = {9, 4, 3, 12 }=

    0 2 3

    D[2] = D[1] + 1 = 2D[11] = D[6] + 1 = 2= =

    5 6

    4

    D[4] = D[0] + 1 = 3D[3] = D[2] + 1 = 3D 12 =D 11 +1 =3

    8

    D[8] = D[9] + 1 = 3

    10 119 12 77

    0 1 2 3 Example (5)

  • 7/28/2019 Week05 Graph 1

    38/69

    0 1 2 3 Example (5)4 765

    8 Q = {5}Q = {1, 6, 10} D[5] = 0

    9 10 11 12= , , ,

    Q = {10, 0, 2, 11 }Q = {0, 2, 11, 9}

    = =D[6] = D[5] + 1 = 1D[10] = D[5] + 1 = 1

    1 20

    , , ,

    Q = {11, 9, 4, 3}Q = {9, 4, 3, 12 }=

    0 2 3

    D[2] = D[1] + 1 = 2D[11] = D[6] + 1 = 2= =

    5 6

    Q = {3, 12, 8}Q = {12, 8, 7}

    = 8 74 7

    D[4] = D[0] + 1 = 3D[3] = D[2] + 1 = 3D 12 =D 11 +1 =3

    Q = {7}Q = {}8

    D[8] = D[9] + 1 = 3D[7] = D[3] + 1 = 4

    10 119 12 This is the BFS = SSSP spanningtree when BFS is started from vertex 5

  • 7/28/2019 Week05 Graph 1

    39/69

    For SSSP on Wei hted Gra h but without Ne ative Wei ht C cle

    DIJKSTRAs

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    40/69

    If the graph is un weighted , we can use BFS

    But what if the ra h is wei hted ? UVa 341 (Non Stop Travel)

    Solution: Dijkstra

    O((V+E)

    log

    V) A Greedy Algorithm

    Use Priority Queue

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    41/69

    3pq = { (0, 2) }

    221

    7We store this pair of information to thepriority queue: (D[vertex], vertex),sorted by increasing D[vertex], and

    06 6then if ties, by vertex number

    See that our priority queue is clean at

    4

    algorithm, it only contains (0, thesource s)

  • 7/28/2019 Week05 Graph 1

    42/69

    3pq = {(0, 2)}

    21

    727

    2pq = , , , , ,

    We greedily take the vertex in the front of the ueue here it is vertex 2 the source

    066

    6

    and then successfully relax all its neighbors(vertex 0, 1, 3).

    4

    r or y ueue w or er ese ver ces as1, 0, 3, with shortest path estimate of 2, 6, 7, respectively.

  • 7/28/2019 Week05 Graph 1

    43/69

    Vertex 3 appears twice in thepriority queue, but this does

    pq = {(0, 2)}3

    not matter, as we will takeonly the first (smaller) one

    pq = , , , , ,pq = { (5, 3) , (6, 0), (7, 3), (8, 4) }2

    172

    52

    066

    6

    the queue (now, it is vertex 1), thensuccessfully relax all its neighbors (vertex 3and 4).

    4Priority Queue will order the items as

    3, 0, 3, 4 with shortest path estimate of , , , , .

  • 7/28/2019 Week05 Graph 1

    44/69

    pq = {(0, 2)}3 pq = , , , , ,

    pq = {(5, 3), (6, 0), (7, 3), (8, 4)}pq = {(6, 0), (7, 3), (8, 4)}2

    172

    52

    066

    6We greedily take the vertex in the front of the queue (now, it is vertex 3), then try torelax all its nei hbors onl vertex 4 .

    4

    However D[4] is already 8. Since D[3] +w(3, 4) = 5 + 5 is worse than 8, we do not

    do anything.

    Priority Queue will now have these items0, 3, 4 with shortest path estimate of 6 7 8 res ectivel .

  • 7/28/2019 Week05 Graph 1

    45/69

    pq = {(0, 2)}3 pq = , , , , ,

    pq = {(5, 3), (6, 0), (7, 3), (8, 4)}pq = {(6, 0), (7, 3), (8, 4)}2

    172

    52

    pq = {(7, 3), (7, 4) , (8, 4)}

    06 6 6 We greedily take the vertex in the front of

    4

    , ,successfully relax all its neighbors (onlyvertex 4).

    Priority Queue will now have these items3, 4, 4 with shortest path estimate of 7, 7, 8, respectively.

  • 7/28/2019 Week05 Graph 1

    46/69

    Remember that vertex 3appeared twice in the priority

    pq = {(0, 2)}3

    ,algorithm will only consider thefirst (shorter) one

    pq = , , , , ,pq = {(5, 3), (6, 0), (7, 3), (8, 4)}pq = {(6, 0), (7, 3), (8, 4)}2

    172

    52

    pq = {(7, 3), (7, 4), (8, 4)}pq = {(7, 4), (8, 4)}

    = (8, 4)06 6 6

    pq = {}

    4Similarly for vertex 4. The one

    with shortest path estimate 7will be processed first and theone with shortest pathestimate 8 will be ignored,

    anymore

  • 7/28/2019 Week05 Graph 1

    47/69

    v st V, I NF ; st s = ; I NF = Bpr i or i t y_queue< i i , vect or , gr eat er > pq;

    pq. push( i i ( 0, s) ) ; / / sor t based on i ncr easi ng di st ancewhi l e ( ! pq. empt y( ) ) { / / mai n l oopi i t op = pq. t op( ) ; pq. pop( ) ; / / gr eedyi nt d = t o . f i r st , u = t o . second;

    i f ( d == di st [ u] ) {f or ( i nt j = 0; j < ( i nt ) Adj Li st [ u] . si ze( ) ; j ++) {

    i f ( di st [ u] + v. second < di st [ v. f i r st ] ) {

    di s t [ v. f i r s t ] = di s t [ u] + v. second; / / r el axpq. push( ( d st [ v. f r st ] , v. f r st ) ) ;} / / enqueue t hi s nei ghbor r egar dl ess i t i s

    } / / al r eady i n pq or not

    }} CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    48/69

    For AllPairs Shortest Paths

    FLOYD WARSHALLs

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    UVa 11463 Commandos 1

  • 7/28/2019 Week05 Graph 1

    49/69

    UVa 11463 Commandos 1AlKhawarizmi, Malaysia National Contest 2008

    Given: A table that stores the amount of minutes to travel

    between buildings (there are at most 100 buildings) 2 special buildings: startB and endB K soldiers to bomb all the K buildings in this mission Each of them start at the same time from startB,

    c oose one ui ing B t at as not een om e y ot er soldier (bombing time negligible),

    .

    What is the minimum time to complete the mission?

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    UVa 11463 Commandos 2

  • 7/28/2019 Week05 Graph 1

    50/69

    UVa 11463 Commandos 2AlKhawarizmi, Malaysia National Contest 2008

    How long do you need to solve this problem?

    Solution: The answer is determined by sp fromstarting building, detonate furthest building ,and sp from that furthest building to end building

    max(dist[start][i] + dist[i][end]) for all i V

    How to compute sp for many pairs of vertices?

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    UVa 11463 Commandos 3

  • 7/28/2019 Week05 Graph 1

    51/69

    UVa 11463 Commandos 3AlKhawarizmi, Malaysia National Contest 2008

    This problem is called: AllPairs Shortest Paths

    Two options

    to

    solve

    this: Call SSSP algorithms multiple times

    Dijkstra O(V * (V+E) * log V), if E = V2 O(V3 log V) Bellman Ford O(V * V * E), if E = V2 O(V4) Slow to code

    Use F oy Wars a , a c ever DP a gorit m O(V3) algorithm

    In this problem, V is

  • 7/28/2019 Week05 Graph 1

    52/69

    O(V3) since we have three nested loops!

    Use adjacency

    matrix:

    G[ MAX_V] [ MAX_V] ; So that weight of edge(i, j) can be accessed in O(1)

    f or ( i nt i = 0; i < V; i ++)f or ( i nt j = 0; j < V; j ++)

    G[ i ] [ j ] = mi n( G[ i ] [ j ] , G[ i ] [ k] + G[ k] [ j ] ) ;

    ee more exp ana on o s ree ner algorithm in CP

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    53/69

    ree, u er rap , rec e cyc c rap as csDAG is also re visited (next week, Week 06)Bi artite Gra h Week 08

    SPECIAL GRAPHS (Part 1)

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    54/69

    4 special graphs frequently appear in contest: Tree, keywords: connected, E = V1, unique path!

    , Actually also rare now

    Directed Acyclic Graph, keywords: no cycle

    Bipartite, keywords: 2 sets, no edges within set!

    Currently not in IOI syllabus

    Some classical hard problems may have faster solution on these special graphs

    Eliminates those who are not aware of the faster solution as solution for

    general graph is slower (TLE)or ar er o co e s ower o ge

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    55/69

    TREE

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    56/69

    Tree is a special Graph. It: Connected Has V vertices and exactly E = V 1 edges Has no cycle

    Has one

    unique

    path

    between

    two

    vertices Sometimes, it has one special vertex called root

    (rooted tree): Root has no parent

    A vertex

    in

    n

    ary

    tree

    has

    either

    {0,

    1,,n}

    children n = 2 is called binary tree (most popular one)

    Has many practical applications: Organization Tree, Directories in Operating System, etc

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    SSSP and APSP Problems

  • 7/28/2019 Week05 Graph 1

    57/69

    on Weighted Tree In general weighted graph

    SSSP roblem: O V+E lo V Di kstrasor O(VE) Bellman Fords 3

    In weighted tree SSSP problem: O(V+E = V+V = V) DFS or BFS

    There is only 1 unique path between 2 vertices in tree APSP problem: simple V calls of DFS or BFS: O(V2)

    But can be made even faster usin LCA not covered

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    Diameter

  • 7/28/2019 Week05 Graph 1

    58/69

    of a Tree In general weighted graph

    We have

    to

    run

    O V

    3 Flo d

    Warshalls

    and

    ick

    the maximum over all dist[i][j] that is not INF

    Do DFS/BFS twice! From any vertex s, find furthest vertex x with DFS/BFS

    Then from vertex x, find furthest vertex y with DFS/BFS

    Answer is the path length of xy O(V+E = V+V = V) only two calls of DFS/BFS

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    59/69

  • 7/28/2019 Week05 Graph 1

    60/69

    Euler Graph

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    61/69

    An Euler path is defined as a path in a graph which visits each edge exactly once

    An Euler tour/cycle is an Euler path which starts and ends on the same vertex

    A graph which has either Euler path or Euler tour is called Eulerian ra h

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    62/69

    To check whether an undirected graph has an Euler tour is simple Check if all its vertices have even degrees.

    Similarly for the Euler path

    An undirected graph has an Euler path if all except two vertices have even degrees and at most two vertices have odd degrees. This Euler path will start from one of these odd degree vertices and end in the other

    Such degree check can be done in O(V + E), usually done simultaneously when reading the input graph

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    63/69

    Knigsberg UVa 291 Non EulerianNon Eulerian Eulerian

    1 1

    2 3 2 3 2 3

    4 4 5 4 5 6

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    64/69

    DIRECTED ACYCLIC GRAPH (DAG)

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    65/69

    Some algorithms become simpler when used on DAGs instead of general graphs, based on the principle of topological ordering

    , paths from a given starting vertex in DAGs in linear time by processing the vertices in a topological order , and calculating the path length for each vertex to be the minimum or maximum length obtained via any of its incoming edges

    , slower algorithms such as Dijkstra's algorithm or the Bellman Ford

    algorithm , and longest paths in arbitrary graphs are NPhard to find

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    Sin leSource Shortest Paths

  • 7/28/2019 Week05 Graph 1

    66/69

    in DAG

    In general weighted graph

    A ain this

    is

    O V+E

    lo

    V

    usin

    Di kstrasor O(VE) using Bellman Fords

    The fact that there is no cycle simplifies this

    pro em su stant a y Simply relax vertices according to topological order!

    s ensure s ortest pat s are compute correct y One Topological sort can be found in O(V+E)

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

    Sin leSource Lon est Paths

  • 7/28/2019 Week05 Graph 1

    67/69

    in DAG

    In general weighted graph

    Lon est

    sim le

    aths is

    an

    NP

    com lete

    roblem

    In DAG T e so ution is t e same as s ortest pat s in DAG,

    just that we have tweak the relax operatoror a ternat ve y, negate a e ge we g t n

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    68/69

    Today, we have quickly gone through various

    wellknown

    ra h

    roblems

    &

    al orithms Depth First Search and Breadth First Search

    Kruskals for MST (briefly) ortest at s pro ems

    BFS (unweighted), Dijkstras (standard), Floyd Warshalls a pa rs, t ree ners

    Special Graph: Tree, Eulerian, DAG

    CS3233 Competitive Programming,Steven Halim, SoC, NUS

  • 7/28/2019 Week05 Graph 1

    69/69

    Note that just knowing these algorithm will not be too useful in contest settin

    You have to practice using them t east co e eac o t e a gor t ms scusse

    today on a contest problem!

    CS3233 Competitive Programming,Steven Halim, SoC, NUS