Shortest paths with 2 constraints (Weight and Colour) - algorithm

Input: We have a directed graph G=(V,E) and each edge has a weight and a colour {red,green}. We are also given a starting node s.Problem/Algorithm: Can we find for all u edges of G, the shortest paths s-u with at most k red edges ? First approach: We save for each node the shortest path with 0,1...k red edges. We modify Dijkstra's algorithm and depending on the colour of the edges we are looking into, we update the distances respectively. This approach fails due to its complexity. Second approach: We make k copies of G graph (G1,G2 ...Gk+1). In order to utilise the k red edges constraint, while we are searching for shortest paths with Dijkstra, every time we "meet" a red edge {ui,vi} in Gi, we connect ui with vi+1 in Gi+1. Because Gk+1 doesn't have any red edges, we can only reach Gk+1 with at most k edges.But it fails. For example with k=2 if a 2 red edges shortest path is found to X node then will not take into consideration a heavier path with less red edges which could lead to an undiscovered node. (If i had enough reputation i could post an image as example). Any ideas ?

I think your approaches are actually equivalent, provided that for approach #1, you record only the shortest distance to each node for each number of red edges used -- you don't need to record the entire path (just as you don't need to record it for ordinary Dijkstra on an ordinary shortest path problem)
Also this approach is sound. In particular, your reasoning that approach #2 is faulty is itself wrong: for any node X in the original graph, there is no single corresponding node X in the new graph; instead there are separate vertices for each number of red edges used. So the two paths "to X" you are considering are not actually to the same node: one is to (X, 2 red edges used) and one is to e.g. (X, 1 red edge used). Then you can use a single Dijkstra run to calculate shortest paths to all k+1 copies of every vertex (i.e. to the vertices (v, i red edges used) for each 0 <= i <= k and for each v in V(G)), and return the lowest. (I'm assuming here that when you wrote "Can we find for all u edges of G, the shortest paths s-u", you meant "for all nodes u of G, the shortest paths s-u".)
Finally, you need to make sure that for any red edge {u, v} in G, you delete the corresponding edge {ui, vi} for all Gi (as well as add in the edge {ui, vi+1}). You probably intended this, but you weren't explicit about it.

Related

Dynamic Programming - Edges difference problem

I just started learning about Dynamic Programming, and in my assignment I was required to describe an algorithm that solves the following problem:
Let G be a directed graph, where every edge is colored either green or yellow, and a source vertex s. For every vertex in V, find a path that the difference between the number of green and yellow edges is minimal. That algorithm needs to be O(|V|+|E|) complexity for each vertex.
Input: Given a directed graph G=(V, E), a source vertex s in V and edges colored with this coloring function: For every edge e in the graph, c(e)->{yellow, green}. There is a path to every vertex v in V from the source vertex s.
The weight of a path 'P' in the graph, is the difference between the number of green edges and the number of yellow edges in the graph
Output: For every vertex v in V, return the minimal weight of a path P from s to v.
So I started thinking about a solution to this problem. I realized that I can exchange the colors with numbers, -1 and 1 and work from there, but so far I haven't been able to find a solution.
My most fleshed out solution looks at the group of neighbors of target a vertex and does the following:
Find the minimum weight between:
The sum of the "weight" of the edge (-1, 1) leading to a vertex 'k' from the current vertex's neighbor group, and the optimum of 'k'.
The optimum of the other neighbors, excluding the vertex 'k'.
terminate when reaching s or the neighbors group is empty.
However, this solution doesn't feel right, as it doesn't look at a vertex - but at a group of vertices, and I don't think it meets the complexity demands. I tried writing the formula: image
I tried experimenting with solutions that start from the vertex s and end at a target vertex v, but I was unable to reach a solid termination condition. For example, it can't terminate when reaching v, since there might be cycles involving v that result in a minimum result.
I was hoping to get some guidance on this problem, thanks in advance!
This doesn't necessarily strike me as a case for dynamic programming, so maybe I've missed something and there's a quicker dynamic solution, but you can achieve an O(VE) running time using a modified Bellman-Ford. This asymptotic time bound is not the same as O(V + E) per vertex! But for a connected graph (since the source can reach all the vertices) it is the same overall.
I'll leave you to look up the details of the Bellman Ford algorithm (for single source shortest paths), in the spirit of it being an assignment, but suffice it to say that your vertices could store a positive score for more yellow than green, a negative score for the opposite, and their weight in either case would be the absolute value of this attribute. Your 'relax' function would then operate as follows, assuming we use a score attribute on each vertex (this score is not the weight, it can be positive or negative):
RELAX(u, v):
new_score = u.score
if the edge u -> v is green:
new_score -= 1
else:
new_score += 1
if abs(new_score) < v.score:
v.score = new_score

Path with the minimum number of alterations in graph with colored edgest

I have a directed graph with colored edges (red & blue) that may contain cycles. The question is to write an algorithm given two vertices (s,t) that finds the path with the minimal number of color changes between s and t (if such path exists).
I have found a solution using a variation of Dijkstra (I created a new graph where each vertex correspond to an edge of the previous graph, and contains the color of the edge. For example: if (1,2) is an edge in the old graph, then (1/2) is a vertex in the new one. I connected "adjacent edges" vertices, and edges in the new graph that change color got a weight of 1, where same color transition is 0).
I am looking for a solution in linear time (of V and E). The above one uses VxE edges in the new graph.
Is there such solution to find the minimal path?
First phase: Reduction to the shortest path problem.
For every node i we create two nodes i_red and i_blue.
For every blue edge i->j we create two edges i_red->j_blue with weight 1 and i_blue->j_blue with weight 0.
We handle red edges in similar fashion.
We also need a start node which is connected with start_red and start_blue with connection weight of 0.
Similar to the target node, which is connected with target_red and target_blue with weight 0-connections.
Now, search for the shortest path from newly created start node to the newly created target node. There are twice as many nodes and twice as many edges as in the original graph, so the reduction is linear.
After you reduced the problem to the shortest path search, you could do the following:
Step: use only edges with weight 0, treat the graph as undirected one and with help of bfs you can find all components in this 0-edge-graph in linear time.
Step: run bfs on the graph where the components from the prior step are glued together as super-nodes, so all edges have weight 1 and bfs will find the shortest path.
Obviously all three parts of this algorithm (bfs in 0-edge-graph, glueing the components to super-nodes and the bfs in the resulting graph) run in linear time.

Show that the heuristic solution to vertex cover is at most twice as large as the optimal solution

The heuristic solution that I've been given is:
Perform a depth-first-search on the graph
Delete all the leaves
The remaining graph forms a vertex cover
I've been given the question: "Show that this heuristic is at most twice as large as the optimal solution to the vertex cover". How can I show this?
I assume that the graph is connected (if it's not the case, we can solve this problem for each component separately).
I also assume that a dfs-tree is rooted and a leaf is a vertex that doesn't have children in the rooted dfs-tree (it's important. If we define it differently, the algorithm may not work).
We need to show to things:
The set of vertices returned by the algorithm is a vertex cover. Indeed, there can be only types of edges in the dfs-tree of any undirected graph: tree edges (such an edge is covered as at least on of its endpoints is not a leaf) and a back edge (again, one of its endpoint is not a leaf because back edge goes from a vertex to its ancestor. A leaf cannot be an ancestor of a leaf).
Let's consider the dfs-tree and ignore the rest of the edges. I'll show that it's not possible to cover tree edges using less than half non-leave vertices. Let S be a minimum vertex cover. Consider a vertex v, such that v is not a leaf and v is not in S (that is, v is returned by the heuristic in question but it's not in the optimal answer). v is not a leaf, thus there is an edge v -> u in the dfs-tree (where u is a successor of v). The edge v -> u is covered by S. Thus, u is in S. Let's define a mapping f from vertices returned by the heuristic that are not in S as f(v) = u (where v and u have the same meaning as in the previous sentence). Note that v is a parent of u in the dfs-tree. But there can be only one parent for any vertex in a tree! Thus, f is an injection. It means that the number of vertices in the set returned by the heuristic but not in the optimal answer is not greater than the size of the optimal answer. That's exactly what we needed to show.
Bad news: heuristics does not work.
Strictly said, 1 isolated vertex is counter-example for the question.
Nevertheless, heuristic does not provide vertex cover solution at all, even if you correct it for isolated vertex and for 2-point cliques.
Take a look at fully connected graphs with number of vertexes from 1 to 3:
1 - strictly said, isolated vertex is not a leaf (it has degree 0, while leaf is a vertex with degree 1), so heuristic will keep it, while vertex cover will not
2 - heuristic will drop both leaves, while vertex cover will keep at least 1 of them
3 - heuristic will leave 1 vertex, while vertex cover has to keep at least 2 vertexes of this clique

Find paths that cover all edges between two nodes

we hope you are able to help us with the following problem:
A directed graph that may contain cycles is given. One has to find a set of paths that fulfill the following criterion:
all edges that can be passed on the way from node A to node B must be covered by the paths within the set (one edge can be part of more than one paths from the set)
the solution does not have to be necessarily the one with the lowest number of paths and the paths does not have to be necessarily the shortest ones. However, the solution should be efficiently implementable using a programming language just as java. We need the solution to generate a few test cases and it is important to cover all edges between a node A and a node B.
does everyone know a suitable algorithm? or does no efficient solution exist?
thanks a lot in advance for your advise! (we have already searched for a solution, but the one we found was focused on shortest paths and were extremely inefficient)
Here is a graphical representation of our problem:
http://i.stack.imgur.com/wIY34.jpg
Consider all edges R(A) reachable from A. They can be found by adding a node on each edge (i.e. turning each edge U->V to U->X->V) and then perform a Breadth First Search starting from A.
Edges outside of R(A) clearly cannot be be on a path from A to B, since then they'd be reachable from A. So all paths to B must go through edges of R(A).
So the set of edges, U, we want to "cover" are all edges of R(A) that B is reachable from.
Now we are looking for a set of paths S from A to B, which contains all edges of U.
A straightforward method is the following:
Color all edges of R(A) black and set S={ }
While there are black edges remaining:
Take a black edge UV.
If B is reachable from V:
Construct a path P = A -> ... -> U -> V -> ... -> B
Color all edges of P as gray
Add P to S
Else:
Color UV as gray.
Then return S
As #user189 pointed out, if we consider reachable edges from A that go through B, we are allowing paths that go twice through B. (I.e. a->b->c->g->f->e in the example image).
His suggested solution (removing the node B before computing R(A) ) fixes this.
Regarding complexity:
R(A) can be computed in O(|E|) time and the paths from A to an edge UV in R(A) can be directly read from the BFS tree. To check for reachability to B from V and to find the path, we can use a BFS tree starting from B and following edges backwards, computed in O(|E|) time.
If we reference the paths implicitly through the edge UV that connects the two BFS trees, and use a O(1) read/update structure to maintain the set of black edges and to look up edges in the BFS trees, I think we can do this in O(|E|) time.

Graph edge traversal algorithm, some edges required, some optional

I have an undirected graph with all vertices of even degree. In this graph there is a set of edges that must be covered exactly once, and a set of edges that should not be covered at all unless absolutely necessary. I need to find a set of one or more paths through the graph such that all of the required edges are covered exactly once, and the number of undesired edges traversed is minimized. No required edge can be traversed by more than one path, but the undesired edges can be traversed by any number of paths. It is not quite a Eulerian path because there are optional edges.
Each individual path's length is limited by a maximum number of required edges it can cover, although a path can cover any number of undesired edges.
The starting points and ending points need not be the same, but there is a set of possible starting points.
Some of the undesired edges are coincident with the required edges -- that is, a pair of vertices might have both a required edge and an undesired edge between them (although there will never be more than one edge of each type between a given pair of vertices).
What's a good algorithm to start with? Fundamentally, I am looking for an algorithm that can find a path that traverses required edges exactly once and avoids undesired edges when possible (but can traverse them more than once if necessary). I can build on that to do the rest.
You are looking for a subgraph within the original graph, such that it contains all the required edges, with a minimum of undesired edges such that it contains an Eulerian path.
It is known that a graph contains an Eulerian path if and only if it is CONNECTED and has all vertices ( except 2 ) of EVEN DEGREE. This can be ensured by doing the following :
Start by directly including all the desired edges in the final subgraph. You now have a graph with one or more connected components.
CASE 1 :
If the number of components in this subgraph is one, (i.e, all the edges are connected to each other ), we only have to ensure that all vertices ( except 2 ) have even degree. Since your original graph does have all vertices of even degree, it is possible to do this, but we also want to take care that the number of edges we add to achieve this is minimum ( since only undesired edges are left to add ).
One good heuristic way to do this, start from each of the odd degree vertices, and do a BFS ( breadth first search ) till you reach another vertex with odd degree. Do this for all the odd degree vertices, choose the 2 vertices which take the maximum undesired path between them to achieve this, and delete this path. Now the graph will have an Eulerian Path
( One thing to note is that such a pairing of odd vertices is always possible, since no graph can have an odd number of vertices of odd degree )
CASE 2 :
The subgraph consisting of only desired edges has more than one component. To ensure connectivity, do the following - Take the component with the minimum number of vertices. Do a BFS from each of the vertices, and choose the minimum length path that connects this component to ANY OTHER component.
Repeat this procedure till all components merge to form a single component. Now for even-ness follow the procedure outlined before for CASE 1.
I think this can be reduced into the Travelling Salesman problem. Create a transformed graph where the nodes represent compulsory edges and the edge weights represent the number of optional edges that must be traversed to get from one compulsory edge to the other.
Now the problem is to find the shortest path in this transformed graph which goes through all the nodes (aka compulsory edges). This is the TSP, which is NP-hard.
There will be some complications because the paths you can take after a compulsory edge depend on the direction in which you took it. You could solve this by turning each compulsory edge into two nodes, one for each direction. The TSP would then have to visit exactly one node from every pair.
e.g.
A===C
| /
| / (edges A<->B and B<->C are compulsory, A<=>C is optional)
|/
B
Transformed graph:
Nodes = { AB, BA, BC, CB }
Edges = { AB -> BC (cost 0), BA -> CB (cost 1), CB -> BA (cost 0), BC -> AB (cost 1) }
This is NP-hard: an instance of the Hamiltonian path problem can be transformed to an instance of your problem. Therefore, if you know how to solve your problem, you know how to solve the Hamiltonian path problem.
To transform, take a directed graph and double each vertex, say, into a red and a blue vertex. For each former vertex, make all inbound edges go to the red vertex, and all outbound edges go out of the blue vertex. Make a single new edge from the red to the blue vertex. Obviously if you can solve the Hamiltonian cycle problem for this graph, you can do so for the original graph.
Now label all new edges compulsory, all the old edges as optional. Mark a single red vertex as a possible entry point. If there's a solution to your problem, then it consists of a single path, which a Hamiltonian path for the original graph.

Resources