CS344-HW4-sol

.pdf
School
Rutgers University**We aren't endorsed by this school
Course
CS 344
Subject
Computer Science
Date
Dec 22, 2024
Pages
15
Uploaded by SargentViper4714
CS 344: Design and Analysis of Computer AlgorithmsRutgers: Fall 2024Homework #4Name(s): FIRST1LAST1, FIRST2LAST2, FIRST3LAST3Homework PolicyIf you leave a question completely blank, you will receive 20% of the grade for that question.Thishowever does not apply to the extra credit questions.You may also consult all the materials used in this course (lecture notes, textbook, slides, etc.) whilewriting your solution, but no other resources are allowed.Unless specified otherwise, you may use any algorithm covered in class as a “black box” – for exampleyou can simply write “sort the array in Θ(nlogn) time using merge sort”.Remember to alwaysprove the correctnessof your algorithms andanalyze their running time(or any other efficiency measure asked in the question). See “Practice Homework” for an example.The extra credit problems are generally more challenging than the standard problems you see in thiscourse (including lectures, homeworks, and exams).As a general rule, only attempt to solve theseproblems if you enjoy them.Groups:You are allowed to form groups of sizetwoorthreestudents for solving each homework (youcan also opt to do it alone if you prefer). The policy regarding groups is as follows:You can pick different partners for different assignments (e.g., from HW1 to HW2) but for anysingle assignment (e.g., HW1), you have to use the same partners for all questions.The members of each group only need to write down and submit a single assignment betweenthem, and all of them will receive the same grade.For submissions, only one member of the group submits the full solutions on Canvas and lists thename of their partners in the group. The other members of the group also need to submit a PDFon Canvas that contains only a single line, stating the name of their partner who has submittedthe full solution on Canvas (Example: SayA,B, andCare in one group;Asubmits the wholeassignment and writes down the namesA,B, andC.BandConly submit a one-page PDF witha single line that says “See the solution ofA”).You are allowed to discuss the questions with any of your classmates even if they are not in yourgroup.But each group must write their solutions independently.1
Background image
Problem 1.Awalkin a directed graphG= (V, E) from a vertexsto a vertext, is a sequence of verticesv1, v2, . . . , vkwherev1=sandvk=tsuch that for anyi < k, (vi, vi+1) is an edge inG. Thelengthof a walkis defined as the number of vertices inside it minus one, i.e., the number of edges (so the walkv1, v2, . . . , vkhas lengthk1).Note that the only difference of a walk with apathwe defined in the course is that a walk can contain thesame vertex (or edge) more than once, while a path consists of only distinct vertices and edges.Design and analyze anO(n+m) time algorithm that given a directed graphG= (V, E) and two verticessandt, outputsYesif there is a walk fromstotinGwhose length is even, andNootherwise.(25 points)Solution.A complete solution consists of three parts, the algorithm (or reduction), proof of correctness,and runtime analysis.The algorithm is by reduction to the graph search problem.Algorithm (reduction):We create a graphG= (V, E) as follows. Vertices ofGare obtained by copyingthe verticesVofGtwo times to gets setsV=V1V2. For any vertexvVandi∈ {1,2}, we usevitodenote the copy ofvinsideViinG. For any edge (u, v)EinsideG, we add the following two edges toE:(u1, v2)and(u2, v1).We then run a graph search algorithm onGfrom the vertexs1V1: if the vertext1V1is reachable inthis search, we returnyes(meaning there is such a walk) and otherwise we returnNo.Proof of Correctness:We prove that there is a walk of even length inGif and only ift1is reachable froms1inG(in the graph search, with no restriction on the length of the walk). This then immediately impliesthe proof by the graph search algorithm we are running onG.An even-length walk fromstotinGimpliest1is reachable froms1inG: LetW=s, u , w , z , y , x ,. . . , tbe the walk inG. Consider the sequenceW=s1, u2, w1, z2, y1, x2,. . . , tinG. This sequence forms a valid walk inGby the definition of edges ofGthat always go fromV1toV2or fromV2toV1(namely, there are no edges with both endpoints inV1nor inV2). Moreover,as the length of the walkWis even, we get that the ending vertex of the walk would bet=t1whichis the vertex we wanted to reach. So there is also a walk froms1tot1inGin this case and thus thealgorithm answers correctly.Ift1is reachable froms1inGthen there is an even-length walk fromstotinG: Consider the pathP=s1, u2, w1, z2, y1, x2,. . . , t1inGwhich exists ast1is reachable froms1. Given the edges of the graphGalways go fromV1toV2orV2toV1, the only way this path can end int1is if its length is a multiple of 2. Given that eachconsecutive pairs of vertices inPcorrespond to a pair inG, this path translates to a walkP=s , u , w , z , y , x ,. . . , tinGwith the same length asP. Thus, there is also an even-length walk fromstotinG.This concludes the proof of correctness.Runtime Analysis:Creating the graphG= (V, E) takesO(n+m) time as we are copying each vertex andedge two times. Running graph search, say by DFS/BFS algorithm, onGalso takes anotherO(2n+ 2m) =O(n+m) time as it has 2nvertices and 2medges. So, total runtime isO(n+m).2
Background image
Problem 2.We have an undirected graphG= (V, E) and two verticessandt. Additionally, we are givena list ofnewedgesFwhich donotbelong to the graphG. For any edgefF, we define the graphGfasthe graph obtained by adding the edgefto the original graphG.Design an algorithm that in timeO(n+m+|F|) finds the edgefFsuch that the distance fromstotinGfis minimized among all choices of an edge fromF.(25 points)Solution.A complete solution consists of three parts, the algorithm (or reduction), proof of correctness,and runtime analysis.Algorithm (reduction):The algorithm is as follows:Run BFS algorithm fromsto computedist(s, v) for all verticesvV.Run BFS algorithm fromtto computedist(v, t) for all verticesvV(note that sinceGis undirected,dist(v, t) =dist(t, v)).For each edgef= (u, v)L, computevalue(f) = min{dist(s, u) + 1 +dist(v, t), dist(s, v) + 1 +dist(u, t)};Return the edgefwith minimumvalue(f).(If thevalue(f)> dist(s, f), you can output ‘no edgehelps in reducing the distance’).Proof of correctness:First note that if adding none of the edgesfLcan reducedist(s, t), then returningany edge inLis a valid solution (becausedist(s, t) always remain the same). So, in the following, we focuson the case that at least adding one of the edges inLreducesdist(s, t).Consider adding any edgefto the graph. Iffreduces the shortest path betweensandt, then it means inthe graphG+f, there is a shortests-tpathPthat contains the edgef. This path will be either a shortestpath (inG) fromstou, take the edgesf= (u, v), and then a shortest path fromvtot, or it will a shortestpath fromstov, take the edge (v, u), and then a shortest path fromutot.So the weight of this pathwill be min{dist(s, u) +wf+dist(v, t), dist(s, v) +wf+dist(u, t)}, the same asvalue(f) computed in thealgorithm. As such, returning the edge with minimumvalueresults in finding the edge that leads to theshortest possibles-tpath.The first two lines takeO(n+m) time by the runtime of BFS. The next for-loop takesO(|F|) time, so thetotal runtime isO(|F|+n+m).3
Background image
Problem 3.LetG= (V, E) be a connected, undirected graph. We start with coins placed on arbitrarilychosen vertices ofG, and each coin can move to an adjacent vertex at every step.The objective is todetermine if it is possible to bring all coins to the same vertex, and if so, compute the minimum number ofmoves required.(a) Suppose there are two coins placed on two given verticesu, vV, which may or may not be distinct.Describe and analyze an algorithm to compute the minimum number of steps to reach a configurationwhere both coins are on the same vertex, or to report correctly that no such configuration is possible.The input to your algorithm consists of the graphG= (V, E) and the initial verticesuandv.(b) Now suppose there are three coins placed on three given vertices ofG.Describe and analyze analgorithm to compute the minimum number of steps to reach a configuration where all three coins areon the same vertex, or to report correctly that no such configuration is possible.(c) Finally, suppose there are forty-two coins placed on forty-two given vertices ofG. Describe and analyzean algorithm to determine whether it is possible to move all 42 coins to the same vertex. For full credit,your algorithm should run inO(V+E) time.(40 points)Solution.We present three solutions based on the several interpretation of what a ”move” is.A) If the coins can move simultaneoulsy and are not requried to move1. Perform a Breadth-First Search (BFS) from each vertexvi(1ik) to compute the shortest pathdistances to all other vertices. Denote these distance arrays asdv1, dv2, . . . , dvk.2. For each vertexxV, check if alldvi[x] (1ik) are finite (i.e., reachable). If so, compute:D(x) = max (dv1[x], dv2[x], . . . , dvk[x]),which represents the minimum time when allkcoins can meet atx.3. Identify the vertexxVthat minimizesD(x). Formally:Dmin= minxVT(x).4. If no suchxexists (i.e., there is no vertex where allkcoins can meet), report that it is not possible tobring all coins to a single vertex.Time Complexity:Each BFS traversal runs inO(V+E).Since we performkBFS traversals, the total complexity isO(k·(V+E)).Checking all vertices for the minimumT(x) adds an additionalO(k·V), which is dominated by theBFS traversals.Thus, the total complexity isO(k·(V+E)).B) If each coin move takes a different time step and coins are not required to moveIn this case, the distance function is replaced byD(x) = (dv1[x] +dv2[x] +. . .+dvk[x])4
Background image
and the rest of the algorithm is the same.C) If every coin moves at every step and is required to moveParity State Graph Solution for two coins:LetG= (V, E) denote the input graph, and letsandtdenote the initial locations of the two coins. Anysequence ofkmoves that brings the two coins to a common vertexxdefines a walk of length 2kfromsthroughxtot. Thus, we are looking for the shortest walk fromstotwith an even length.To solve this, we reduce the problem to a standard shortest-path problem in a new state graphG= (V, E),that remembers the parity of the length of the walk, defined as follows:V=V× {0,1}={(v, b)|vVandb∈ {0,1}}.E={(u, b)(v,1b)|uvEandb∈ {0,1}}.Edges inGare undirected because the edges in the original graphGare undirected.For any walkv0v1v2→ · · · →vinG, there is a corresponding walk inGgiven by:(v0,0)(v1,1)(v2,0)→ · · · →(v, ℓmod 2).Thus, every even-length walk fromstotinGcorresponds to a walk from (s,0) to (t,0) inG, and viceversa.1. Construct the graphG:For every vertexvV, create two vertices (v,0) and (v,1) inV.For every edgeuvEinG, add two edges inE:(u,0)(v,1)and(u,1)(v,0).2. Perform a Breadth-First Search (BFS) starting from (s,0) inGto compute the shortest-path distances.3. If (t,0) is reached during the BFS, the shortest path distance gives the length of the shortest even-lengthpath fromstotinG.4. If (t,0) is not reached, report that there is no even-length path fromstotinG.AnalysisConstructingGinvolves creatingV= 2Vvertices andE= 2Eedges, which takesO(V+E) time.BFS onGalso takesO(V+E) =O(V+E) time.Thus, the overall time complexity of the algorithm isO(V+E).Parity Construction Solution for Multiple Coins:We claim that a sequence ofksteps moves all coins to a vertextif and only if, for each coin starting atsi,there exists a walk of lengthkifromsitotsuch thatk= maxiki, and either allkiare even or all are odd.Proof:If all coins move totinksteps, thenki=kfor alli, satisfying the condition. Conversely, any walkof lengthkican be extended to a walk of lengthkkiby addingkkisteps, maintaining parity, allowingsynchronization attink= maxikisteps.For any vertexvand coin starting atsi, define:5
Background image
deven(si, v): Length of the shortest even-length walk fromsitov(orif none exists).dodd(si, v): Length of the shortest odd-length walk fromsitov(orif none exists).MinSteps(v) = min{maxideven(si, v),maxidodd(si, v)}: Minimum steps to move all coins tov.To compute min{MinSteps(v)|vV}, construct an auxiliary graphG= (V, E), where:V=V× {0,1}, with (v, b) representing vertexvwith parityb(even or odd).E={(u,0)(v,1),(u,1)(v,0)|uvE}, toggling parity between vertices.Perform BFS inGfrom each (si,0) to compute:deven(si, v) =d((si,0),(v,0)),dodd(si, v) =d((si,0),(v,1)),whered(u, v) is the shortest path inG.Finally, compute MinSteps(v) for allvVand find the vertex minimizing it.ConstructingGtakesO(V+E) time, and BFS for each coin takesO(V+E). Computing MinSteps(v) addsO(V), resulting intotal complexityO(V+E).6
Background image
Problem 4.Consider a directed graphG, where each edge is colored either red, white, or blue. A walk inGis called a French flag walk if its sequence of edge colors is red, white, blue, red, white, blue, and so on.More formally, a walkv0v1→ · · · →vkis a French flag walk if, for every integeri, the edgevivi+1isred ifimod 3 = 0, white ifimod 3 = 1, and blue ifimod 3 = 2.Describe an algorithm to find all vertices inGthat can be reached from a given vertexvthrough a Frenchflag walk.(25 points)Solution.State Graph ConstructionConstruct an auxiliary state graphG= (V, E) as follows:V=V× {0,1,2}, where each (u, s) represents a vertexuVin states:s= 0 (red),s= 1 (white),s= 2 (blue).Econtains edges (u, s)(v,(s+ 1)mod 3) if:s= 0 anduvis red,s= 1 anduvis white,s= 2 anduvis blue.Algorithm1. ConstructG.2. Perform BFS inGstarting from (v,0).3. Collect all verticesuVreachable inG.Claim:The auxiliary graphG= (V, E) ensures that any path inGcorresponds to a valid French flagwalk inG, and vice versa.Proof:Each vertex (v, s)Vrepresents vertexvVwith the current expected edge colors, where:s= 0 (red),s= 1 (white),s= 2 (blue).An edge (u, s)(v,(s+ 1)mod 3) exists inGif and only ifuvinGhas the correct color forstates. This ensures the walk alternates in the sequence red, white, blue.Starting BFS at (v,0) guarantees all paths inGcorrespond to valid French flag walks inG, as:(v0,0)(v1,1)(v2,2)→ · · · →(vk, kmod 3).Conversely, any French flag walkv0v1→ · · · →vkinGmaps to a path inGby following this statetransition.ComplexityConstructingGtakesO(V+E) time, with 3|V|vertices and 3|E|edges.BFS inGruns inO(V+E).Thus, the total complexity isO(V+E), and the algorithm efficiently identifies all vertices reachable througha French flag walk.7
Background image
Problem 5.A vertexvin a connected undirected graphGis called a cut vertex if the subgraphGv(obtained by removingvfromG) is disconnected.Describe an algorithm that identifies every cut vertex in a given undirected graph inO(V+E) time.(25 points)Solution.We use Depth-First Search (DFS) to find all cut vertices.DFS Tree: A tree formed during the DFS traversal ofG.Discovery Time (d[v]): The time when vertexvis first visited in DFS.Low Value (low[v]): The smallest discovery time of any vertex reachable fromv, includingvitself and itsdescendants in the DFS tree.Key Observation:A vertexvis a cut vertex if:(1)vis the root of the DFS tree and has more than one child.(2)vis not the root, and there exists a childuofvsuch that low[u]d[v].Algorithm:1. Initialize arraysd[v], low[v], and a parent array parent[v] for all vertices.2. Perform DFS from any vertexv:For each vertexuadjacent tov:Ifuis unvisited, mark it as a child ofv, updated[u] and low[u], and recurse.Ifuis visited but is not the parent ofv, update low[v] = min(low[v], d[u]).After visiting all children ofv, check the conditions forvbeing a cut vertex:If root: more than one childorIf non-root: low[u]d[v].Complexity Analysis:Each vertex and edge is visited exactly once during DFS, making the time complexityO(V+E).Proof: Correctness of Maintaining low[v]:The low[v] value for a vertexvrepresents the smallest discovery time of any vertex reachable fromvor itsdescendants in the DFS tree, including back edges. This is updated during the DFS as follows:1.Initialization:Whenvis first visited in DFS, low[v] is initialized to its discovery time:low[v] =d[v].This ensures that initially, low[v] only considersvitself.2.Update Rule for Child Vertices:When exploring a childuofvin the DFS tree:Ifuis unvisited, DFS is recursively called onu. After the recursion, low[v] is updated to consider thesmallest reachable vertex inu’s subtree:low[v] = min(low[v],low[u]).This ensures that low[v] reflects not onlyvbut also all vertices reachable throughuand its descendants.8
Background image
Ifuis already visited and is not the parent ofv, thenuforms a back edge to an ancestor ofv. In thiscase, low[v] is updated as:low[v] = min(low[v], d[u]).This ensures that low[v] also accounts for back edges, which provide additional paths to earlier verticesin the DFS tree.3.Correctness of Updates:During DFS, every descendant ofvis processed beforevfinishes. Thus, bythe time the recursion backtracks tov, low[u] for all childrenuofvhas been finalized. This guaranteesthat low[v] incorporates the smallest discovery time of all reachable vertices.4.Key Property:The low[v] value ensures that:low[v] = min(d[v],minuchildren(v)low[u],minwback edges(v)d[w]),wherewrepresents vertices reachable through back edges fromv. This accounts for all paths throughdescendants and back edges.9
Background image
Problem 6.Suppose we are given a directed acyclic graph (DAG)G= (V, E) whose nodes represent jobs,and whose edges represent precedence constraints. Specifically, each edgeuvindicates that jobumustbe completed before jobvcan begin. Each nodevalso has a weightT(v) indicating the time required toexecute jobv.(a) Describe an algorithm to determine the shortest interval of time in which all jobs inGcan be completed.(b) Suppose the first job starts at time 0.Describe an algorithm to determine, for each vertexv, theearliest time at which jobvcan begin.(c) Now describe an algorithm to determine, for each vertexv, the latest time at which jobvcan beginwithout violating the precedence constraints or increasing the overall completion time (computed inpart (a)), assuming that every job exceptvstarts at its earliest start time (computed in part (b)).(40points)Solution.I will describe the solutions in both serial and parallel execution models:Parallel Execution:Part (a): Shortest Interval to Complete All JobsLetf[v] as the earliest completion time of jobv. The algorithm proceeds as follows:1. Compute a topological ordering of the vertices using DFS. Let the order bev1, v2, . . . , vn.2. Process vertices in topological order. For each vertexv, update:f[v] =T(v) + maxuvf[u],whereuare the predecessors ofv. Ifvhas no predecessors,f[v] =T(v).3. The shortest interval of time to complete all jobs is:Completion Time = maxvVf[v].Complexity:Topological sorting takesO(V+E). Processing vertices also takesO(V+E). Thus, the totalcomplexity isO(V+E).Part (b): Earliest Start Time for Each JobDefine EST(v) as the earliest time jobvcan begin. The algorithm is:1. Reuse thef[v] values from part (a). For each vertexv:EST(v) = maxuvf[u],whereuare the predecessors ofv. Ifvhas no predecessors, EST(v) = 0.2. Process nodes in topological order to compute EST(v) for allv.Complexity:The algorithm processes each edge and vertex once, resulting inO(V+E).Part (c): Latest Start Time for Each JobDefine LST(v) as the latest time jobvcan start without increasing the overall completion time. LetC=maxvVf[v], the total completion time. The algorithm is:1. Initialize:LST(v) =CT(v)ifvhas no successors.10
Background image
2. Process nodes in reverse topological order. For each vertexv:LST(v) = minvw(LST(w)T(v)),whereware the successors ofv.Complexity:Processing vertices and edges in reverse topological order takesO(V+E).Serial Execution:Part (a): Shortest Interval to Complete All JobsThis doesn’t depend on the order of execution and we haveCompletion Time =XvVT[v].Part (b): Earliest Start Time for Each JobPart (c): Latest Start Time for Each Job11
Background image
Problem 7.Tarjan’s algorithm is an efficient method for finding all strongly connected components (SCCs)of a directed graphG= (V, E) in linear time.A strongly connected component of a directed graph is amaximal subgraph in which any two vertices are reachable from each other. Tarjan’s algorithm leveragesDepth-First Search (DFS) to identify these components, ensuring each node in the graph is part of exactlyone SCC.The main idea of Tarjan’s algorithm is to perform a DFS onG, keeping track of each vertex’s discoverytimev.index (a unique integer assigned in the order of discovery) and a secondary valuev.lowlink, which isthe smallest discovery index reachable fromvin the DFS subtree, includingvitself. The key steps of thealgorithm are as follows:1. For each unvisited vertexvinG, initiate a DFS that assignsv.index andv.lowlink.2. Push each visited vertex onto a stack, and keep it on the stack until its strongly connected componenthas been fully explored.3. For each successorwofv:Ifwhas not yet been visited, recursively call the DFS onw. Updatev.lowlink as min(v.lowlink, w.lowlink).Ifwis on the stack, updatev.lowlink as min(v.lowlink, w.index).4. After visiting all descendants ofv, ifv.lowlink =v.index, thenvis the root of a strongly connectedcomponent. Pop vertices from the stack untilvis removed, forming one complete SCC.Using the above description, prove the correctness of Tarjan’s algorithm. In particular, demonstrate that:The algorithm correctly identifies each strongly connected component.Each vertex belongs to exactly one SCC.The invariant properties ofv.index andv.lowlink are maintained throughout the execution of thealgorithm.(25 points)Solution.The algorithm computes lowlink function defined as follows: for each vertexv,v.lowlink is thesmallest discovery time (or preorder number) among all vertices reachable fromvthrough a path consistingof tree edges (from the depth-first search tree) followed by at most one back edge. Formally:v.lowlink = min{x.index : vertexxis reachable fromvby such a path}.Correctness of thelowlinkCalculation:The lowlink property is maintained during the depth-first search (DFS) as follows:1. Initially,v.lowlink =v.index whenvis first discovered.2. When exploring a tree edge to an unvisited neighborw, the DFS propagatesw.lowlink back tov,ensuringv.lowlink = min(v.lowlink, w.lowlink).3. When encountering a back edge to an ancestoruon the stack,v.lowlink is updated to includeu.index:v.lowlink = min(v.lowlink, u.index).The above rules ensure thatv.lowlink is the smallest index of any vertex reachable fromvthroughboth forward and back edges.Key observations include:12
Background image
1. For any vertexv,v.lowlinkv.index, becausevcan reach itself through zero tree edges and zero backedges.2. Ifv.lowlink =v.index, thenvis the root of a strongly connected component (sink component in theDFS forest).3. The stack invariants ensure that all vertices in the same strongly connected component appear consec-utively on the stack.Lemma.A vertexvis the root of a sink component ofGif and only ifv.lowlink=v.index andw.lowlink<w.index for every proper descendantwofv.Proof.1.()Supposevis the root of a sink componentC. Then:(a) All vertices inCare reachable fromv.(b)vcannot reach any vertex outsideC, so no descendantwofvcan reach a vertex with a discoverytime less thanv.index.(c) By definition,v.lowlink =v.index becausevcannot reach any vertex outsideC.(d) For any proper descendantwofv,w.lowlink< w.index becausewcan reach a vertexxinCwithx.index< w.index.2.()Supposev.lowlink =v.index andw.lowlink< w.index for every proper descendantwofv. Then:(a) By definition ofv.lowlink,vcannot reach any vertexxwithx.index< v.index, sovcannot reachits parent in the DFS tree.(b) All descendants ofvare part of the same strongly connected componentC, becausevand itsdescendants form a mutually reachable set.(c) Sincevcannot reach any vertex outsideC,Cis a sink component, andvis its root..13
Background image
Problem 8.Suppose we are given both an undirected graphGwith weighted edges and a minimum spanningtreeTofG.(a) Describe an algorithm to update the minimum spanning tree when the weight of a single edgeeisdecreased.(b) Describe an algorithm to update the minimum spanning tree when the weight of a single edgeeisincreased.(25 points)Solution.a) When the weight of one edgeeTis decreased.In this case, the given MSTTis still an MST. While this may seem obvious, we argue it carefully here.LetTbe the MST, andWbe the weight ofT. Lete= (u, v), and let the decrease in weight bed, sothat the new weight ofTbecomesWd. LetTbe a new MST, andWbe the weight ofT. Wethen haveWWd. On the other hand, the original weight ofTis at mostW+d, since as wereturn to the original weights, the weight of only one edgeeincreases byd. SinceTis the MST withrespect to the original weights, we haveWW+d. It follows thatW=Wd. So,Thas the sameweight asTγwith respect to the new weights, and thus is still an MST.b) When the weight of one edgee /Tis increased.In this case, the given MSTTis still a MST. To see this, consider a run of Kruskal’s algorithm whichproducedT. All of the same decisions would be made whenehas a higher weight, and so the sametree will be produced. (This assumes the edge weights are unique. A more subtle argument is neededif the edge weights are not unique.)c) When the weight of one edgeeTis increased.Lete= (u, v) and letTuandTvbe the subtrees obtained by removinge. By doing BFS (ignoring edgeweights) fromuand fromv, we can determine which vertices are inTuand which are inTvin timeO(|V|+|E|). (Actually, we can do this inO(|V|), since we only need to consider edges of the treeT,but the next step will takeO(|E|) anyway.) Assume we have marked each node with its membership.Now examine each edge, and keep the minimum weight edgeewith one endpoint inTuand the otherinTv. This can be done inO(|E|) time. The total time is thusO(|V|+|E|). (Okay, we could perhapsspeed this up by examining only those edges adjacent to vertices ofTu. thus ignoring edges with bothendpoints inTv.) Can you argue why the resulting tree is an MST?d) When the weight of one edgee /Tis decreased.Lete= (u, v). AddetoTwhich will create a unique cycle, which we can find doing BFS inT∪ {e}starting fromuand ignoring weights. This takesO(|T|) =O(|V|) time. Now remove the maximumweight edge on that cycle (O(|V|)). Can you argue why the resulting tree is an MST?14
Background image
Challenge Yourself.Suppose you are given an arbitrary directed graphGin which each edge is coloredeither red or blue, along with two special verticessandt.(a) Describe an algorithm that either computes a walk fromstotsuch that the pattern of red and blueedges along the walk is a palindrome, or correctly reports that no such walk exists.(b) Describe an algorithm that either computes the shortest walk fromstotsuch that the pattern of redand blue edges along the walk is a palindrome, or correctly reports that no such walk exists.15
Background image