Вы находитесь на странице: 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.

CS3233 Competitive p Programming g g


Dr.StevenHalim Week05 Graph1(Basics)

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Outline(1)
MiniContest#4+Break+Discussion Admins CS2010/2020Reviews(notdiscussedindetailsexceptredones)
Graph:Preliminary&Motivation Graph G hTraversal T lAlgorithms Al ith
DFS/BFS:ConnectedComponents/FloodFill DFSonly:Toposort/CutVertex+Bridges/StronglyConnectedComponents

MinimumSpanningTreeAlgorithm
KruskalsandPrims:PlusVariousApplications

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Outline(2)
CS2010/2020 / Reviews(notdiscussedindetailsexceptredones)
SingleSourceShortestPaths
BFS:SSSPonUnweightedgraph/Variants Dijkstras:SSSPonWeighted(novecycle)graph/Variants

AllPairsShortestPaths
FloydWarshalls+Variants

SpecialGraphsPart1
Tree, Tree EulerGraph Graph,DirectedAcyclicGraph

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

GraphTerms QuickReview
Vertices/Nodes / Edges Un/Weighted Un/Directed In/OutDegree SelfLoop/MultipleEdges ( l (Multigraph) h)vsSimple l Graph Sparse/Dense S /D Path,Cycle Isolated, I l t d Reachable R h bl (Strongly)Connected Component Sub S bG Graph h CompleteGraph Directed Di d A Acyclic li G Graph h Tree/Forest Euler/Hamiltonian l / l Path/Cycle Bipartite Bi tit G Graph h

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Kaohsiung g2006
Standings &FelixsAnalysis
A. PrintWords d inLines B. TheBugSensorProblem C PitcherRotation C. D. LuckyandGoodMonths E. RoutePlanning ShiftCipher(N/AinLiveArchive) F. ASchedulingProblem G Check G. Ch kthe h Li Lines H. PerfectService A. DP B. Graph,MST C DP+memoryreduction C. D. TediousAdHoc E. Search? CompleteSearch+STL F. Greedy? G ? G. H. DAGraph,DPonTree

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Singapore g p 2007
Standings&FelixsAnalysis
A. B. C C. D. E. F. G. MODEX JONES ACORN TUSK SKYLINE USHER RACING A. B. C C. D. E. F. G. Math, h Modulo d l Arithmetic h DP DP+memoryreduction Geometry DS,SegmentTree Graph,APSP,MinWeightedCycle++ Graph,MaximumSpanningTree

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Jakarta2008
Standings&SuhendrysAnalysis
A. B. C C. D. E. F. G. H H. I. J J. AntiBruteForceLock k BonusTreasure PandaLand7:CasinoIsland DisjointPaths ExpertEnough? FreeParentheses GreatestKPalindromeSub H Hyper Mod M d ICPCTeamStrategy JollybeeTournament A. B. C C. D. E. F. G. H H. I. J J. Graph, h MST Recursion Trie? DAGraph,DPonTree CompleteSearch(isenough) DP,harderthanproblemI String M h Math DP,medium AdHoc, Hoc Simulation

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

KualaLumpur2008
A. B. C C. D. E. F. G. H H. I. J J. K. ASCIIDiamondi d MatchMaker TariffPlan IrreducibleFractions GunFight UnlocktheLock IronmanRaceinTreeland Sh i the Shooting h Monster M AdditionSubstractionGame TheGreatGame TriangleHazard A. B. C C. D. E. F. G. H H. I. J J. K. Ad dHoc DP,StableMarriageProblem? AdHoc Math Graph,MCBM(AlternatingPath) Graph,SSSP(BFS) DAGraph,LikelyDPonTree? C Comp Geo G ? ? Math

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Daejeon2010
A. B. C C. D. E. F. G. H H. I. J J. Sales l StringPopping Password Mines BinarySearchTree TourBelt StringPhone I Installations ll i Restaurant KTXTrainDepot A. B. C C. D. E. F. G. H H. I. J J. BruteForce RecursiveBacktracking RecursiveBacktracking Geometry+SCCs(Graph) Graph,BST,Math,Combinatoric Graph,MST(modified) ? ? ? ?

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

DepthFirstSearch(DFS) BreadthFirstSearch(BFS)
Reachability FindingConnectedComponents FloodFill TopologicalSort FindingCycles(BackEdges) FindingArticulationPoints&Bridges FindingStrongly ConnectedComponents

GRAPHTRAVERSALALGORITHMS

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Motivation(1)
HowtosolvetheseUVaproblems:
469 ( (WetlandsofFlorida) )
Similarproblems:260,352,572,782,784,785,etc

11504 (Dominos)
Similarproblems:1263,11709,etc

With Without tfamiliarity f ili it with ithDepth D thFirst Fi tS Search h algorithmanditsvariants,theylookhard

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Motivation(2)
HowtosolvetheseUVaproblems:
336 ( (ANodeTooFar) )
Similarproblems:383,439,532,762,10009,etc

WithoutfamiliaritywithBreadthFirstSearch graphtraversalalgorithm, theylookhard

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

GraphTraversalAlgorithms
Givenagraph,wewanttotraverse it! Thereare2majorways:
DepthFirstSearch(DFS)
Usually U ll implemented i l t dusing i recursion i Morenatural Most M f frequently l used dtotraverseagraph h

BreadthFirstSearch(BFS)
Usuallyimplementedusingqueue(+map),useSTL Cansolvespecialcase*ofshortestpathsproblem!
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

DepthFirstSearch Template
O(V+E)ifusingAdjacencyList O(V2)ifusingAdjacencyMatrix
typedef pair<int, int> ii; typedef vector<ii> vi; void dfs(int u) { // DFS for normal usage printf(" %d", u); // this vertex is visited dfs_num[u] = DFS_BLACK; // mark as visited for (int j = 0; j < (int)AdjList[u].size; j++) { ii v = AdjList[u][j]; // try all neighbors v of vertex u if (dfs_num[v.first] == DFS_WHITE) // avoid cycle dfs(v.first); // v is a (neighbor, weight) pair } }
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

BreadthFirstSearch(usingSTL)
Complexity:alsoO(V+E)usingAdjacencyList
map<int, <i t i int> t> di dist; t di dist[source] t[ ] = 0 0; queue<int> q; q.push(source); // start from source while hil (! (!q.empty()) t ()) { int u = q.front(); q.pop(); // queue: layer by layer! for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjLi AdjList[u][j]; t[ ][j] // f for each h neighbours i hb of f u if (!dist.count(v.first)) { dist[v.first] = dist[u] + 1; // unvisited + reachable q.push(v.first); h( fi t) // enqueue v.first fi t f for next t steps t } } }
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

st 1

Application:ConnectedComponents
Acallofdfs( (u)visitsonly yverticesconnectedtou

DFS(andBFS)canfindconnectedcomponents

int numComp = 0; dfs_num.assign(V, DFS_WHITE); REP (i, 0, V - 1) // for each vertex i in [0..V-1] if (dfs (dfs_num[i] num[i] == DFS DFS_WHITE) WHITE) { // if not visited yet printf("Component %d, visit", ++numComp); dfs(i); // one component found printf("\n"); } printf("There p ( are %d connected components\n", p , numComp); p);
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Finding Fi di T Topological l i lS Sort t(see ( text t t b book/CS2010/CS2020) k/CS2010/CS2020) FindingArticulationPointsandBridges(seetextbook) FindingStronglyConnectedComponent

TARJANSDFSALGORITHMS

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

TarjansSCC
Input: A Directed Graph dfs_num: visitation counter df l dfs_low: l lowest t df dfs_num reachable h bl f from th that t vertex t using the current DFS spanning tree
dfs_num(0) = 0 dfs_low(0) = 0 dfs_num(1) = 1 dfs_num(3) = 2 dfs_low(1) = 1 dfs_low(3) = 1 dfs_num(4) = 4 dfs_num(5) = 5 dfs_low(4) = 4 dfs_low(5) = 4

0 1 3 2

DFS S Spanning i Tree

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

4 6

5 7
DAG after contracting SCCs

4 5 7 6

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

13 2

45 76

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Code:TarjansSCC(notinIOIsyllabus)
vi dfs_num, dfs_low, S, visited; // global variables void tarjanSCC(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; // dfs_low[u] <= dfs_num[u] S.push_back(u); // stores u in a vector based on order of visitation visited[u] = 1; for (int j = 0 0; j < (int)AdjList[ (int)AdjList[u].size(); ] si e() j++) { ii = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) // a tree edge j ( ); tarjanSCC(v.first); if (visited[v.first]) // condition for update dfs_low[u] = min(dfs_low[u], dfs_low[v.first]); // update dfs_low[u] } if (dfs_low[u] == dfs_num[u]) { // if this is a root (start) of an SCC printf("SCC %d: ", ++numSCC); // this part is done after recursion while (1) { int v = S S.back(); back(); S S.pop_back(); pop back(); visited[v] = 0; printf(" %d", v); if (u == v) break; } printf("\n"); } }

GraphTraversalComparison
DFS Pros:
Slightlyeasierto code Uselessmemory

BFS Pros:
CansolveSSSPon unweightedgraphs (discussedlater)

Cons:
CannotsolveSSSPon unweightedgraphs

Cons:
Slightly g ylonger g to code Usemorememory

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Primsalgorithm Readtextbookonyourown (orreviseCS2010/CS2020material)

KRUSKALSALGORITHMFOR MINIMUMSPANNINGTREE
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

HowtoSolveThis?
Giventhisgraph,selectsomeedgess.t theg graph p isconnected 2 butwithminimaltotalweight!
2 5 5 8 5 8

MST!

5
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

SpanningTree&MST
Givenaconnectedundirected graphG, selectE Gsuchthatatreeisformedand thistreespans (covers)allV G!
Nocyclesorloopsareformed!

Therecanbeseveral spanningtreesinG
Theonewheretotalcostisminimum iscalledtheMinimum SpanningTree(MST)

UVa:908 (ReconnectingComputerSites)
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Example
Th Original The Oi i lG Graph h A Spanning S i T Tree Cost: 4+4+6+6 = 20 An MST A Cost: 4+6+6+2 = 18

1
4 6

1
4 6

1
4 6

0
6

2
8

0
6

2
8

0
6

2
8

3
9

3
9

3
9

AlgorithmsforFindingMST
Prims(GreedyAlgorithm)
Atevery yiteration, ,chooseanedge g with minimumcostthatdoesnotformacycle
grows grows anMSTfromaroot

Kruskals(alsoGreedyAlgorithm)
Repeatedly dl finds fi d edges d with i hminimum i i costs thatdoesnotformacycle
formsanMSTbyconnectingforests

Whichoneiseasiertocode?
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Kruskals Kruskal sAlgorithm


Inmyopinion,Kruskalsalgorithmissimpler
sort edges by increasing weight O(E log E) while there are unprocessed edges left O(E) pick an edge e with minimum cost adding g e to MST S does not ot form o a cyc cycle e if add add e to MST

SimplystoretheedgesinanarrayofEdges (EdgeList)andsortthem,orusePriorityQueue Test T tfor f cycles l using i Disjoint Di j i tSets S t (Union (U i Find) Fi d)DS

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Kruskals Kruskal sAnimation(1)


The original Th i i l graph, h no edge is selected Connect C t 1 and d2 As this edge is smallest Connect C t 1 and d0 No cycle is formed

1
4 6

1
4 6

1
4 6

0
6

2
8

0
6

2
8

0
6

2
8

3
9

3
9

3
9

4
Note: The sorted order of the edges determines how the MST formed. Observe that we can also choose to connect vertex 2 and 0 also with weight 4!

Kruskals Kruskal sAnimation(2)


Cannot C t connect t 0 and d2 As it will form a cycle Connect C t 0 and d3 The next smallest edge Connect C t 0 and d4 MST is formed

1
4 6

1
4 6

1
4 6

0
6

2
8

0
6

2
8

0
6

2
8

3
9

3
9

3
9

4
Note: Again, Again the sorted order of the edges determines how the MST formed; Connecting 0 and 4 is also a valid next move

Kruskals Kruskal sAnimation(3)


But B t (standard) ( t d d) Kruskals K k l algorithm will still continue However, it will H ill not t modify anything else This i Thi is th the fi final l MST with cost 18

1
4 6

1
4 6

1
6

0
6

2
8

0
6

2
8

0
6

2 3

3
9

3
9

Kruskals Kruskal sAlgorithm(SampleCode)


// sorted d b by edge d cost vector< pair<int, ii> > EdgeList; // insert edges in format (weight, (u, v)) to EdgeList sort(EdgeList.begin(), Edgelist.End(); mst_cost mst cost = 0; initSet(V); // all V are disjoint initially for (int I = 0; I < E; i++) {// while more edges pair<int, ii> front = EdgeList[i]; if (!isSameSet(front.second.first, front.second.second)) { // if adding e to MST does not form a cycle st_cost cost += front.first; o t. st; // add t the e weight e g t o of e to MST S mst unionSet(front.second.first, front.second.second); } }
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

But But
YouhavenotteachusUnionFindDSinCS3233??
ItisalsoonlycoveredbrieflyinCS2010/CS2020

Yeah,wechoosetoskipthatDSinCS3233 IfyouwanttosolveMSTproblems, learnUnionFindDSonyourown(Sec2.3.2) Tobefair, fair Iwillnot setanyMSTproblemsinCS3233 minicontestsproblemsA+B


IdonotsayanythingaboutproblemCormid/finalcontest

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

BFS(unweighted) Dijk t ( Dijkstras (nonvecycle) l ) BellmanFords(mayhavevecycle),notdiscussed FloydWarshalls Warshall s(allpairs

SHORTESTPATHS

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

BFSforSpecialCase SSSP
SSSPisaclassicalprobleminGraphtheory:
Findshortestp pathsfromonesource totherest^

Specialcase:UVa336 (ANodeTooFar) ProblemDescription:


Givenanunweighted g &undirectedGraph, p , astartingvertexv,andanintegerTTL Checkhowmanynodesareunreachablefromv orhasdistance>TTLfromv
i.e. i e length(shortest_path shortest path(v, (v node))>TTL
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

0 4 8 9

1 5

2 6

3 7
Q = {5}

Example(1)
D[5] = 0

10

11

12

0 4 8 9

1 5

2 6

3 7
Q = {5} Q = {1, 6, 10}

Example(2)
D[5] = 0 D[1] = D[5] + 1 = 1 D[6] = D[5] + 1 = 1 D[10] = D[5] + 1 = 1

10 1 5

11

12

10

0 4 8 9 0

1 5

2 6

3 7
Q = {5} Q = {1, 6, 10} Q = {6, {6 10, 10 0, 0 2} Q = {10, 0, 2, 11} Q = {0, 2, 11, 9}

Example(3)
D[5] = 0 D[1] = D[5] + 1 = 1 D[6] = D[5] + 1 = 1 D[10] = D[5] + 1 = 1 D[0] = D[1] + 1 = 2 D[2] = D[1] + 1 = 2 D[11] = D[6] + 1 = 2 D[9] = D[10] + 1 = 2

10 1 5

11 2 20 6

12

10

11

0 4 8 9 0 4 8 9

1 5

2 6

3 7
Q = {5} Q = {1, 6, 10} Q = {6, {6 10, 10 0, 0 2} Q = {10, 0, 2, 11} Q = {0, 2, 11, 9} Q = {2, {2 11, 11 9 9, 4} Q = {11, 9, 4, 3} Q = {9, 4, 3, 12} Q = {4, 3, 12, 8}

Example(4)
D[5] = 0 D[1] = D[5] + 1 = 1 D[6] = D[5] + 1 = 1 D[10] = D[5] + 1 = 1 D[0] = D[1] + 1 = 2 D[2] = D[1] + 1 = 2 D[11] = D[6] + 1 = 2 D[9] = D[10] + 1 = 2 D[4] = D[0] + 1 = 3 D[3] = D[2] + 1 = 3 D[12] = D[11] + 1 = 3 D[8] = D[9] + 1 = 3

10 1 5

11 2 20 6

12 3

10

11

12

77

0 4 8 9 0 4 8 9

1 5

2 6

3 7
Q = {5} Q = {1, 6, 10} Q = {6, {6 10, 10 0, 0 2} Q = {10, 0, 2, 11} Q = {0, 2, 11, 9} Q = {2, {2 11, 11 9 9, 4} Q = {11, 9, 4, 3} Q = {9, 4, 3, 12} Q = {4, 3, 12, 8} Q = {3, 12, 8} Q = {12, 8, 7} Q = {8, { , 7} } Q = {7} Q = {}

Example(5)
D[5] = 0 D[1] = D[5] + 1 = 1 D[6] = D[5] + 1 = 1 D[10] = D[5] + 1 = 1 D[0] = D[1] + 1 = 2 D[2] = D[1] + 1 = 2 D[11] = D[6] + 1 = 2 D[9] = D[10] + 1 = 2 D[4] = D[0] + 1 = 3 D[3] = D[2] + 1 = 3 D[12] = D[11] + 1 = 3 D[8] = D[9] + 1 = 3 D[7] = D[3] + 1 = 4

10 1 5

11 2 20 6

12 3 7

10

11

12

This is the BFS = SSSP spanning tree when BFS is started from vertex 5

ForSSSPonWeightedGraphbutwithoutNegativeWeightCycle

DIJKSTRAs

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

SingleSource ShortestPaths(1)
Ifthegraphisunweighted,wecanuseBFS
Butwhatiftheg graph p isweighted g ?

UVa341 (NonStopTravel) Solution:DijkstraO((V+E) (( )logV) )


AGreedy yAlgorithm g UsePriorityQueue

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

ModifiedDijkstra Dijkstras s Example(1)


3
pq = {(0, 2)}

20 2 6

7 6

3
5

We store this pair of information to the priority queue: (D[vertex], vertex), sorted by increasing D[vertex], and then if ties, by vertex number See that our priority queue is clean at the beginning of (modified) Dijsktra Dijsktras s algorithm, it only contains (0, the source s)

0
1

ModifiedDijkstra Dijkstras s Example(2)


3

1 2

20 2 6

7 6
6

3 7
5

pq = {(0, 2)} {(2 1) 1), (6, (6 0) 0), (7, (7 3)} pq = {(2,


We greedily take the vertex in the front of e queue (here, ( e e, it is s vertex e e 2, , the e source), sou ce), the and then successfully relax all its neighbors (vertex 0, 1, 3). Priority P i it Q Queue will ill order d th these 3 vertices ti as 1, 0, 3, with shortest path estimate of 2, 6, 7, respectively.

0
1

ModifiedDijkstra Dijkstras s Example(3)


Vertex 3 appears twice in the priority queue, but this does not matter, as we will take only the first (smaller) one

1 2

202 6

7 6
60

3 5
5 1

pq = {(0, 2)} pq = {(2, {(2 1) 1), (6, (6 0) 0), (7 (7, 3)} pq = {(5, 3), (6, 0), (7, 3), (8, 4)}
We greedily take the vertex in the front of the queue (now, it is vertex 1), then successfully relax all its neighbors (vertex 3 ) and 4). Priority Queue will order the items as 3, 0, 3, 4 with shortest path estimate of 5 6 5, 6, 7 7, 8 8, respectively respectively.

84

ModifiedDijkstra Dijkstras s Example(4)


3

1 2

20 2 6

7 6
6

3 5
5

pq = {(0, 2)} pq = {(2, {(2 1) 1), (6, (6 0) 0), (7 (7, 3)} pq = {(5, 3), (6, 0), (7, 3), (8, 4)} pq = {(6, 0), (7, 3), (8, 4)}
We greedily take the vertex in the front of the queue (now, it is vertex 3), then try to relax all its neighbors (only vertex 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 items 0, 3, 4 with shortest path estimate of , 7, , 8, , respectively. p y 6,

0
8

ModifiedDijkstra Dijkstras s Example(5)


3

1 2

20 2 6

7 6
6

3 5
5

pq = {(0, 2)} pq = {(2, {(2 1) 1), (6, (6 0) 0), (7 (7, 3)} pq = {(5, 3), (6, 0), (7, 3), (8, 4)} pq = {(6, 0), (7, 3), (8, 4)} pq = {(7, 3), (7, 4), (8, 4)}
We greedily take the vertex in the front of the queue (now, (now it is vertex 5) 5), then successfully relax all its neighbors (only vertex 4). Priority Queue will now have these items 3, 4, 4 with shortest path estimate of 7, 7, 8, respectively.

0
1
7

ModifiedDijkstra Dijkstras s Example(6)


3

1 2

20 2 6

7 6
6

3 5
5

0
1
7

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

Remember that vertex 3 appeared twice in the priority queue but this Dijkstra queue, Dijkstras s algorithm will only consider the first (shorter) one

Similarly for vertex 4. The one with shortest path estimate 7 will be processed first and the one with shortest path estimate 8 will be ignored, although nothing is changed anymore

Dijkstras Dijkstra sAlgorithm(usingSTL)


vi i di dist(V, ( INF); ) di dist[s] [ ] = 0 0; // INF = 2 2B priority_queue< ii, vector<ii>, greater<ii> > pq; pq.push(ii(0, s)); // sort based on increasing distance while (!pq.empty()) { // main loop ii top = pq.top(); pq.pop(); // greedy p , u = top.second; p ; int d = top.first, if (d == dist[u]) { for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; // all outgoing edges from u if (dist[u] + v.second < dist[v.first]) { dist[v.first] = dist[u] + v.second; // relax pq.push(ii(dist[v.first], ii i i v.first)); i } // enqueue this neighbor regardless it is } // already in pq or not } CS3233 CompetitiveProgramming, }
StevenHalim,SoC,NUS

ForAllPairsShortestPaths

FLOYD WARSHALLs

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

UVa11463 Commandos(1) ( )
AlKhawarizmi,MalaysiaNationalContest2008 Given:
Atablethatstorestheamountofminutestotravel betweenbuildings(thereareatmost100 buildings) 2specialbuildings:startBandendB KsoldierstobomballtheKbuildingsinthismission EachofthemstartatthesametimefromstartB, choose h oneb building ildi Bthat h has h notb beenb bombed b d b byother h soldier(bombingtimenegligible), andthengatherin(destroyed)buildingendB endB.

Whatistheminimumtimetocompletethemission?
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

UVa11463 Commandos(2) ( )
AlKhawarizmi,MalaysiaNationalContest2008 Howlongdoyouneedtosolvethisproblem? Solution:
Theanswerisdeterminedbyspfrom startingbuilding,detonatefurthestbuilding, andspfromthatfurthestbuildingtoendbuilding
max(dist[start][i]+dist[i][end])foralli V

Howtocomputesp formany pairsofvertices?

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

UVa11463 Commandos(3) ( )
AlKhawarizmi,MalaysiaNationalContest2008 Thisproblemiscalled:AllPairsShortestPaths Twooptionstosolvethis:
CallSSSPalgorithmsmultipletimes
DijkstraO(V*(V+E)*logV),ifE=V2 O(V3 logV) BellmanFordO(V*V*E),ifE=V2 O(V4) Slowtocode

UseFloyd l dWarshall, h ll aclever l DP algorithm l ih


O(V3)algorithm Veryeasy tocode! Inthisproblem,Vis<=100,soFloydWarshallisDOABLE!!

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

FloydWarshall Template
O(V3)sincewehavethreenestedloops! Useadjacencymatrix:G[MAX_V][MAX_V] _ _ ;
Sothatweightofedge(i,j)canbeaccessedinO(1)
for (int k = 0; k < V; k++) for (int i = 0; i < V; i++) j++) for (int j = 0; j < V; j G[i][j] = min(G[i][j], G[i][k] + G[k][j]);

SeemoreexplanationofthisthreelinerDP algorithminCP
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Tree,E T Euler l G Graph, h Directed Di t dAcyclic A li Graph G h(basics) (b i ) DAGisalsorevisited(nextweek,Week06) BipartiteGraph(Week08)

SPECIALGRAPHS(Part1)

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

SpecialGraphsinContest
4specialgraphsfrequentlyappearincontest:
Tree,keywords:connected,E=V1,uniquepath! EulerianGraph Graph,keywords:mustvisiteachedgeonce
Actuallyalsorarenow

DirectedAcyclicGraph,keywords:nocycle Bipartite,keywords:2sets,noedgeswithinset!
CurrentlynotinIOIsyllabus

Someclassical l lh hard problems bl mayh have fastersolution onthesespecialgraphs


Thisallowsproblemsettertoincreaseinputsize!
Eliminatesthosewhoarenotawareofthefastersolutionassolutionfor generalgraphisslower(TLE) orharder h d to t code d (slower (l to t get tAC) AC)
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

TREE

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Tree
TreeisaspecialGraph.It:
Connected HasVverticesandexactlyE=V 1edges Hasnocycle Hasoneuniquepathbetweentwovertices Sometimes,ithasonespecialvertexcalledroot (rootedtree):Roothasnoparent Avertexinnarytreehaseither{0,1,,n}children
n=2iscalledbinarytree(mostpopularone)

Hasmanypracticalapplications:
OrganizationTree,DirectoriesinOperatingSystem,etc
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

SSSPandAPSPProblems
onWeightedTree Ingeneralweightedgraph
SSSPp problem:O((V+E) (( )log gV) )Dijkstras j orO(VE)BellmanFords APSPproblem:O(V3)FloydWarshall Warshalls s

Inweightedtree
SSSPproblem:O(V+E =V+V =V)DFSorBFS
Thereisonly1uniquepathbetween2verticesintree

APSPproblem:simpleVcallsofDFSorBFS:O(V2)
Butcanbemadeevenfasterusing gLCAnotcovered
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Diameter
ofaTree Ingeneralweightedgraph
WehavetorunO(V ( 3)Floyd y Warshallsandpick p themaximumoveralldist[i][j]thatisnotINF

Inweightedtree
DoDFS/BFStwice!
Fromanyvertexs,findfurthestvertexxwithDFS/BFS Thenfromvertexx,findfurthestvertexywithDFS/BFS Answeristhepathlengthofxy O(V+E=V+V=V)only twocallsofDFS/BFS
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

TreeIllustration
A

0 1 2

B1

0 1 0

B2

0 1 2

5 0
3 4

5 2
1

5 0
3

3
4

3
2

3
4

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

EulerGraph

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

EulerianGraph(1)
AnEulerpath isdefinedasapathinagraphwhich visitseachedgeexactlyonce AnEulertour/cycle isanEulerpathwhichstartsand endsonthesamevertex AgraphwhichhaseitherEulerpathorEulertouris called ca edEulerian u e a graph g ap

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

EulerianGraph(2)
TocheckwhetheranundirectedgraphhasanEuler tourissimple
Checkifallitsverticeshaveevendegrees.

SimilarlyfortheEulerpath
AnundirectedgraphhasanEulerpathifallexcepttwo verticeshaveevendegreesandatmosttwoverticeshave odddegrees.ThisEulerpathwillstartfromoneofthese odddegreeverticesandendintheother

SuchdegreecheckcanbedoneinO(V+E),usually donesimultaneouslywhenreadingtheinputgraph
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

EulerianGraph(3)
Knigsberg Non Eulerian UVa 291 Eulerian Non Eulerian

1 2 4 3 2 4

1 3 5 2 4

1 3 5

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

DIRECTEDACYCLICGRAPH(DAG)

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

DirectedAcyclicGraph(DAG)
SomealgorithmsbecomesimplerwhenusedonDAGsinsteadof generalgraphs,basedontheprincipleoftopologicalordering Forexample, example itispossibletofind shortestpaths and longest paths fromagivenstartingvertexinDAGsinlineartime by processingtheverticesinatopologicalorder,andcalculatingthe pathlengthforeachvertextobetheminimumormaximumlength obtainedviaanyofitsincomingedges Incontrast contrast,forarbitrarygraphstheshortestpathmayrequire sloweralgorithmssuchas Dijkstra'salgorithm orthe BellmanFord algorithm,andlongestpathsinarbitrarygraphsare NPhard tofind

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Single g SourceShortestPaths
inDAG Ingeneralweightedgraph
Again g thisisO((V+E) (( )log gV) )using gDijkstras j orO(VE)usingBellmanFords

InDAG
Thefactthatthereisnocyclesimplifiesthis problem bl substantially! b i ll !
Simplyrelaxverticesaccordingtotopologicalorder! Thi ensureshortest This h paths h arecomputed dcorrectly! l ! OneTopologicalsortcanbefoundinO(V+E)
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Single g SourceLongest g Paths


inDAG Ingeneralweightedgraph
Longest g ( (simple) p )p pathsisanNPcomplete p p problem

InDAG
The Th solution l i is i the h sameasshortest h paths h in i DAG, DAG justthatwehavetweaktherelaxoperator ( alternatively, (or l i l negateall lledge d weight i h i inDAG)

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Summary(1)
Today,wehavequickly gonethroughvarious wellknowng graph p problems p &algorithms g
DepthFirstSearchandBreadthFirstSearch
ConnectedversusStrongly ConnectedComponents

KruskalsforMST(briefly) Shortest Sh P Paths h problems bl


BFS(unweighted),Dijkstras(standard),FloydWarshalls ( llpairs, (all i three h liners) li )

SpecialGraph:Tree,Eulerian,DAG
CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Summary(2)
Notethatjustknowingthesealgorithmwill notbetoousefulincontestsetting g Youhavetopracticeusingthem
Atleast l tcode d each hof fth thealgorithms l ith discussed di d todayonacontestproblem!

CS3233 CompetitiveProgramming, StevenHalim,SoC,NUS

Вам также может понравиться