Proof of correctness: Algorithm for diameter of a tree in graph theory - algorithm

In order to find the diameter of a tree I can take any node from the tree, perform BFS to find a node which is farthest away from it and then perform BFS on that node. The greatest distance from the second BFS will yield the diameter.
I am not sure how to prove this, though? I have tried using induction on the number of nodes, but there are too many cases.
Any ideas would be much appreciated...

Let's call the endpoint found by the first BFS x. The crucial step is proving that the x found in this first step always "works" -- that is, that it is always at one end of some longest path. (Note that in general there can be more than one equally-longest path.) If we can establish this, it's straightforward to see that a BFS rooted at x will find some node as far as possible from x, which must therefore be an overall longest path.
Hint: Suppose (to the contrary) that there is a longer path between two vertices u and v, neither of which is x.
Observe that, on the unique path between u and v, there must be some highest (closest to the root) vertex h. There are two possibilities: either h is on the path from the root of the BFS to x, or it is not. Show a contradiction by showing that in both cases, the u-v path can be made at least as long by replacing some path segment in it with a path to x.
[EDIT] Actually, it may not be necessary to treat the 2 cases separately after all. But I often find it easier to break a configuration into several (or even many) cases, and treat each one separately. Here, the case where h is on the path from the BFS root to x is easier to handle, and gives a clue for the other case.
[EDIT 2] Coming back to this later, it now seems to me that the two cases that need to be considered are (i) the u-v path intersects the path from the root to x (at some vertex y, not necessarily at the u-v path's highest point h); and (ii) it doesn't. We still need h to prove each case.

I'm going to work out j_random_hacker's hint. Let s, t be a maximally distant pair. Let u be the arbitrary vertex. We have a schematic like
u
|
|
|
x
/ \
/ \
/ \
s t ,
where x is the junction of s, t, u (i.e. the unique vertex that lies on each of the three paths between these vertices).
Suppose that v is a vertex maximally distant from u. If the schematic now looks like
u
|
|
|
x v
/ \ /
/ *
/ \
s t ,
then
d(s, t) = d(s, x) + d(x, t) <= d(s, x) + d(x, v) = d(s, v),
where the inequality holds because d(u, t) = d(u, x) + d(x, t) and d(u, v) = d(u, x) + d(x, v). There is a symmetric case where v attaches between s and x instead of between x and t.
The other case looks like
u
|
*---v
|
x
/ \
/ \
/ \
s t .
Now,
d(u, s) <= d(u, v) <= d(u, x) + d(x, v)
d(u, t) <= d(u, v) <= d(u, x) + d(x, v)
d(s, t) = d(s, x) + d(x, t)
= d(u, s) + d(u, t) - 2 d(u, x)
<= 2 d(x, v)
2 d(s, t) <= d(s, t) + 2 d(x, v)
= d(s, x) + d(x, v) + d(v, x) + d(x, t)
= d(v, s) + d(v, t),
so max(d(v, s), d(v, t)) >= d(s, t) by an averaging argument, and v belongs to a maximally distant pair.

Here's an alternative way to look at it:
Suppose G = ( V, E ) is a nonempty, finite tree with vertex set V and edge set E.
Consider the following algorithm:
Let count = 0. Let all edges in E initially be uncolored. Let C initially be equal to V.
Consider the subset V' of V containing all vertices with exactly one uncolored edge:
if V' is empty then let d = count * 2, and stop.
if V' contains exactly two elements then color their mutual (uncolored) edge green, let d = count * 2 + 1, and stop.
otherwise, V' contains at least three vertices; proceed as follows:
Increment count by one.
Remove all vertices from C that have no uncolored edges.
For each vertex in V with two or more uncolored edges, re-color each of its green edges red (some vertices may have zero such edges).
For each vertex in V', color its uncolored edge green.
Return to step (2).
That basically colors the graph from the leaves inward, marking paths with maximal distance to a leaf in green and marking those with only shorter distances in red. Meanwhile, the nodes of C, the center, with shorter maximal distance to a leaf are pared away until C contains only the one or two nodes with the largest maximum distance to a leaf.
By construction, all simple paths from leaf vertices to their nearest center vertex that traverse only green edges are the same length (count), and all other simple paths from a leaf vertex to its nearest center vertex (traversing at least one red edge) are shorter. It can furthermore be proven that
this algorithm always terminates under the conditions given, leaving every edge of G colored either red or green, and leaving C with either one or two elements.
at algorithm termination, d is the diameter of G, measured in edges.
Given a vertex v in V, the maximum-length simple paths in G starting at v are exactly those that contain contain all vertices of the center, terminate at a leaf, and traverse only green edges between center and the far endpoint. These go from v, across the center, to one of the leaves farthest from the center.
Now consider your algorithm, which might be more practical, in light of the above. Starting from any vertex v, there is exactly one simple path p from that vertex, ending at a center vertex, and containing all vertices of the center (because G is a tree, and if there are two vertices in C then they share an edge). It can be shown that the maximal simple paths in G having v as one endpoint all have the form of the union of p with a simple path from center to leaf traversing only green edges.
The key point for our purposes is that the incoming edge of the other endpoint is necessarily green. Therefore, when we perform a search for the longest paths starting there, we have access to those traversing only green edges from leaf across (all vertices of) the center to another leaf. Those are exactly the maximal-length simple paths in G, so we can be confident that the second search will indeed reveal the graph diameter.

1:procedureTreeDiameter(T)
2:pick an arbitrary vertex v where v∈V
3:u = BFS ( T, v )
4:t = BFS ( T, u )
5:return distance ( u, t )
Result: Complexity = O(|V|)

Related

Create an algorithm for computing the shortest path with constraints on the vertices in O(m + nlogn)

So I'm trying to write an algorithm for computing the shortest path with constraints on the vertices you can visit in O(m + nlogn) time. In this problem, we are given an indirect weighted (non negative) graph G = (V, E), a set of vertices X ⊂ V, and two vertices s, t ∈ V \ X. The graph is given with adjacency lists and we can assume that it takes O(1) time to determine if a vertex is in X. I'm trying to write an algorithm which can compute the shortest path between s and t in G such that the path includes at most one vertex from X if such a path exists in O(m + nlogn) time. I know that this algorithm would require a modified Dijkstra's algorithm but I'm unsure how to proceed from here. Could anyone please help me out? Thank you
Construct a new graph by taking two disjoint copies of your graph G (call them G0 and G1), and for each edge (v, x) in G (with x in X), add an additional edge in the combined graph from v in G0 to x in G1. This new graph has twice as many vertices as G, and at most three times as many edges.
The shortest path from s in G0 to t in G1 is the shortest path from s to t in G going through at least one vertex of X.
On this new graph, Dijkstra's algorithm (with the priority queue implemented with a fibonacci heap) works in time O(3m + 2n log 2n) = O(m + n log n).
A possibility is to double the number of vertices not in X.
For each vertex v not in X, you create v0 and v1: v0 is accessible only without passing from a vertex in X, v1 is accessible by passing through one and only one vertex in X.
Let us call w another vertex. Then:
if w is in X, v not in X:
length (w, v0) = infinite and dist(v1) = min (dist(v1), dist(w) + length(w, v))
if w is in X, v in X:
length (w, v) = infinite
if w is not in X, v not in X:
dist (v0) = min (dist(v0), dist (w0) + length (w, v))
dist (v1) = min (dist(v1), dist (w1) + length (w, v))
if w is not in X, v is in X:
dist (v) = min (dist(v), dist (w0) + length (w, v))

Question : Minimal routes through preferred vertices

I need help to solve this question:
you have a graph G=(V,E) , nodes pair s ≠ t ∈ V and you have subset of nodes U ⊆ V Which exists ø ≠ U ≠ V and s,t ∉ U.
for each path P we mark it L(P) the length of the path (number of edges in the path) and #P(U) number of the nodes U in the path, write an algorithm to find a path between from s to t that should visit U exactly 2 times And the minimum length of all these tracks.
In other words the algorithm should return a path from s to t where #P(U)=2 and lets say we have another path P' from s to t where #P'(U)=2 then L(P)≤ L(P')
( it is permissible for the track to pass through A certain vertex more than once) .
Help : use graph reduction G'
Divide the trajectory into 5 steps
{s} ∪X → U → X∪ {ε} → U → X∪ {t} where X = V \\ (U∪ {s, t}) (X group of vertices out of V that are not Preferred vertices, neither s nor t) which will ensure that #P (U) = 2 and we will use BFS to find the shortest route.
Algorithm -
Constructed from G (V, E) New directional graph G ^ '= (V ^', E ^ ') as follows:
Each preferred vertex u∈U, we add twice to V ^ 'so u_4∈V ^', u_2∈V ^ '. We will add s and t to the new graph and for each x∈X vertex we will create x_1, x_3, x_5 in the new graph.
For each arc (s, x) ∈E | x∈X, {(s, x_1)} ∈E ^ '
Per arc (s, u) ∈E | u∈U, {(s, u_2)} ∈E ^ '
For each arc (x, u) ∈E | x∈X, u∈U, {(x_1, u_2), (x_3, u_4)} ∈E ^ '
Per arc (u, x) ∈E | u∈U, x∈X, {(u_2, x_3), (u_4, x_5)} ∈E ^ '
Per arc (u, u ') ∈E | u, u'∈U, {(u_2, u_4 ^ ')} ∈E ^'
Per arc (u, t) ∈E | u∈U, {(u_4, t)} ∈E ^ '
For each arc (x, t) ∈E | x∈X, {(x_5, t)} ∈E ^ '
We will now run a BFS scan on graph G 'starting from s. For the first appearance of t in the scan, the trajectory from s to t (after lowering the labels for there to be a trajectory in G) is the shortest trajectory that satisfies the question conditions. If no t is found in the scan - then there is no such trajectory.
The correctness of the algorithm -
#P (U) = 2 - By defining the graph G 'we guarantee that each trajectory from s to t will pass exactly twice in the vertices of U (this can be seen by labeling the vertices to stages 1-5 and arcs that always progress in stages without the possibility of skipping stages 2 and 4 where there are vertices of U).
The shortest route - using a BFS scan ensures acceptance of the shortest route, because the scan is performed at levels when a vertex that appeared at an earlier level - will not appear at a later level.
Finally, the labels are lowered to ensure that the route is in G.
Complexity of the algorithm -
The graph G 'is constructed by going over all the vertices and arcs of G once and therefore ran in Θ (m + n), scanning BFS over G' running in Θ (m + n) (by BFS runtime) and we obtained that the runtime The total is Θ (m + n).
Previous solution presented by 'evyatar weiss' is partial, since it's not considering the fact that you can move within X uninterruptedly (U is limited to 2 vertices per route, but X is not limited). Following is an example of a graph to which this solution will not work (I added in pencil the missing vertices in order to fix it).
In order to solve this, the following vericies should be added to G':
For each arc (x,x')∈E | x,x'∈X, {(x_1, x'_1), (x_3, x'_3), (x_5, x'_5)}∈E'

Find the Optimal vertex cover of a tree with k blue vertices

I need to find a 'dynamic - programming' kind of solution for the following problem:
Input:
Perfect Binary-Tree, T = (V,E) - (each node has exactly 2 children except the leafs).
V = V(blue) ∪ V(black).
V(blue) ∩ V(black) = ∅.
(In other words, some vertices in the tree are blue)
Root of the tree 'r'.
integer k
A legal Solution:
A subset of vertices V' ⊆ V which is a vertex cover of T, and |V' ∩ V(blue)| = k. (In other words, the cover V' contains k blue vertices)
Solution Value:
The value of a legal solution V' is the number of vertices in the set = |V'|.
For convenience, we will define the value of an "un-legal" solution to be ∞.
What we need to find:
A solution with minimal Value.
(In other words, The best solution is a solution which is a cover, contains exactly k blue vertices and the number of vertices in the set is minimal.)
I need to define a typical sub-problem. (Like, if i know what is the value solution of a sub tree I can use it to find my value solution to the problem.)
and suggest a formula to solve it.
To me, looks like you are on the right track!
Still, I think you will have to use an additional parameter to tell us how far is any picked vertex from the current subtree's root.
For example, it can be just the indication whether we pick the current vertex, as below.
Let fun (v, b, p) be the optimal size for subtree with root v such that, in this subtree, we pick exactly b blue vertices, and p = 1 if we pick vertex v or p = 0 if we don't.
The answer is the minimum of fun (r, k, 0) and fun (r, k, 1): we want the answer for the full tree (v = r), with exactly k vertices covered in blue (b = k), and we can either pick or not pick the root.
Now, how do we calculate this?
For the leaves, fun (v, 0, 0) is 0 and fun (v, t, 1) is 1, where t tells us whether vertex v is blue (1 if yes, 0 if no).
All other combinations are invalid, and we can simulate it by saying the respective values are positive infinities: for example, for a leaf vertex v, the value fun (v, 3, 1) = +infinity.
In the implementation, the infinity can be just any value greater than any possible answer.
For all internal vertices, let v be the current vertex and u and w be its children.
We have two options: to pick or not to pick the vertex v.
Suppose we pick it.
Then the value we get for f (v, b, 1) is 1 (the picked vertex v) plus the minimum of fun (u, x, q) + fun (w, y, r) such that x + y is either b if the vertex v is black or b - 1 if it is blue, and q and r can be arbitrary: if we picked the vertex v, the edges v--u and v--w are already covered by our vertex cover.
Now let us not pick the vertex v.
Then the value we get for f (v, b, 0) is just the minimum of fun (u, x, 1) + fun (w, y, 1) such that x + y = b: if we did not pick the vertex v, the edges v--u and v--w have to be covered by u and w.

Find two paths in a graph that are in distance of at least D(constant)

Instance of the problem:
Undirected and unweighted graph G=(V,E).
two source nodes a and b, two destination nodes c and d and a constant D(complete positive number).(we can assume that lambda(c,d),lambda(a,b)>D, when lambda(x,y) is the shortest path between x and y in G).
we have two peoples standing on the nodes a and b.
Definition:scheduler set-
A scheduler set is a set of orders such that in each step only one of the peoples make a move from his node v to one of v neighbors, when the starting position of them is in the nodes a,b and the ending position is in the nodes c,d.A "scheduler set" is missing-disorders if in each step the distance between the two peoples is > D.
I need to find an algorithm that decides whether there is a "missing-disorders scheduler set" or not.
any suggestions?
One simple solution would be to first solve all-pairs shortest paths using n breadth-first searches from every node in O(n * (n + m)).
Then create the graph of valid node pairs (x,y) with lambda(x, y) > D, with edges indicating the possible moves. There is an edge {(v,w), (x,y)} if v = x and there is an edge {w, y} in the original graph or if w = y and there is an edge {v, x} in the original graph. This new graph has O(n^2) nodes and O(nm) edges.
Now you just need to check whether (c, d) is reachable from (a, b) in the new graph. This can be achieved using DFS or BFS.
The total runtime be O(n * (n + m)).

Prove traversing a k-ary tree twice yields the diameter

I've known the algorithm to find the diameter of a tree mentioned here for quite some time:
Select a random node A
Run BFS on this node to find furthermost node from A. name this node as S.
Now run BFS starting from S, find the furthermost node from S, name it D.
Path between S and D is diameter of the tree.
But why does it work?
I would accept both Ivan's and coproc's answer if I can. These are 2 very different approaches that both answer my question.
say S = [A - B - C - D - ... X - Y - Z] is the diameter of the tree.
consider each node in S, say #, start from it and go "away" from the diameter, there won't be a longer chain than min(length(#, A), length(#, Z)).
so dfs from any node on the tree, it will ends at A or 'Z', i.e. one end of the diameter, dfs again from it will of course lead you to the other side of the tree.
refer to this
Suppose you've completed steps 1 and 2 and have found S, and that there is no diameter in the tree that includes S. Pick a diameter PQ of the tree. You basically have to check the possible cases and in all of them, find that either PS or SQ is at least as long as PQ - which would be a contradiction.
In order to systematically check all cases, you can assume that the tree is rooted at A. Then the shortest path between any two vertices U and V is calculated in the following way - let W be the lowest common ancestor of U and V. Then the length of UV is equal to the sum of the distances between U and W and between V and W - and, in a rooted tree, these distances are just differences in the levels of the nodes (and S has a maximum level in this tree).
Then analyze all possible positions S could take with respect to the subtree rooted at W (lowest common ancestor of P and Q) and the vertices P and Q. For example, the first case is simple - S is not in the subtree rooted at W. Then, we can trivially improve the path by selecting the one of P and Q that is more distant to the root, and connecting it to the S. The rest of the cases are similar.
This algorithm works for any acyclic graph (a tree being a special acyclic graph in that it has a root).
A proof can be constructed by choosing any two additional points S2 and D2 and showing that their distance d(S2,D2) ≤ d(S,D). From the algorithm we know
by step 2: d(A,S)≥d(A,D), d(A,S)≥d(A,S2), d(A,S)≥d(A,D2) and
by step 3: d(S,D)≥d(S,A), d(S,D)≥d(S,S2), d(S,D)≥d(S,D2).
By distinguishing at most 5 cases (e.g. the paths SD and S2D2 have no edge in common, the paths SD and S2D2 have edges in common and A is connected to the edges running to S, etc. see image below) one can decompose the above distances into sub-paths and rewrite the inequalities based on the sub-paths. The conclusion follows from simple algebra. The details are left to the reader as an exercise. :-)
A few lemmas/facts before we get started with proof.
T is a tree so there is exactly 1 path between any 2 pair of vertices.
If S--D is the diameter then a BFS with source as S (or D) will end up giving D (or S) the largest distance. (By definition of diameter)
Also lets define |XY| to be the length of the path X--Y.
Define |XX| = 0.
Let A be the random node selected by the algorithm.
After Step 2 let the furthest node got be P.
If P is either S or D then using Lemma 2 we are done. So we must show that P has to be either S or D.
Claim : If S--D is the diameter, then P is either S or D.
Proof: I am going to prove the above by proving the Contrapositive. The proof is for a tree with a unique diameter but it should work with minor changes (mostly the equalities) for non-unique diameters too.
If P is neither S nor D then S--D is not the diameter.
Assume P is neither S nor D.
Case 1: The Path A--P intersects S--D
Let the point of intersection be K. We know that BFS marked P as the farthest node from A and from Lemma 1.
|AP| > |AS|
|AK| + |KP| > |AK| + |KS|
Therefore we get |KP| > |KS|.
Similarly |KP| > |KD|.
Now we consider the path SP
|SP| = |SK| + |KP|
|SP| > |SK| + |KD|
|SP| > |SD|
So SP is longer than the diameter which means SD is NOT the diameter.
Case 2:The Path A--P does NOT intersects S--D
Now we know BFS marked P as the farthest node. So we have
|AP| > |AD|
|AP| > |AS|
We can write |AD| = |AK| + |KD| where K is one of the vertices in the diameter (including S and D). Similarly |AS| = |AK| + |KS|.
Without loss of generality assume |AD|>=|AS|
|AK| + |KD| >= |AK| + |KS|
|KD| >= |KS|
Now consider the path PD
|PD| = |AP| + |AD|
|PD| = |AP| + |AK| + |KD|
|PD| > |AP| + |KD| (|AK| > 0 since A cannot be on the diameter)
|PD| > |KD| + |KD| (|AP| > |KD|)
|PD| > |SK| + |KD| (|KD| >= |KS|)
|PD| > |SD|
So SD is not the diameter and hence the claim.
Let the Set s represents the nodes along the diameter of the tree, with A and Z being the end nodes, and the distance from A to Z is the diameter. For any node, n, that is a member of s the longest possible path from n will end in either A or Z. Now if you pick a rand node in the tree, v, it either is a member of the set, or it has a path to a node, n, in this set. Since the longest path from n is either A or Z and the path from v to n can not be longer than either the path from n to A or n to Z (if it was then v would have to be a member of the set) then running BFS on any node V will first find either A or Z, and the subsequent call will find the complementary end point. Not a math girl, just throwing out thoughts.

Resources