is it possible to find a spanning tree for a direct and unweighted graph? - data-structures

I try to explain my problem better.
in input I have the number of nodes N and the number of edges P.
N represent the cities while P the water pipes.
So for example in input I have 4 and 2 {0,1,2,3,4} would be my graph
and the 2 represents me the already existing water pipes
since in the following lines of the file I will have the already
existing connections so since in this case I have the 2 for example in
the file I'll have 3-1 and 2-1. so at the beginning I will have a
graph with 5 vertices and an edge that goes from node 3 to node 1 and
another arc that goes from 2 to 1.
now I have to determine how many and which connections to make to
bring water to all the cities. so for example in this case a solution
could be 0-4,0-3,0-2.
NOTE 0 represents the dam basin.
I was thinking that this problem seems to me very similar to MST but the graph I have is oriented and not weighted so I cannot apply the Prim or Kruskal algorithm.
So since it doesn't make sense to apply MST maybe I could do this via a DFS or a BFS but I don't quite understand how.
I believe that if I do a dfs from the source then from node 0 and I see all the nodes that I have not been able to reach and I connect these nodes to the source I have the solution but I have not understood how to do it.
or would it be better to try to make l mst work on this type of graph then cloning it and adding weights = 1 to the arcs?

" I know I can't apply it for the type of graph I have"
How do you know this?
Unweighted. Make your graph weighted by applying a weight of 1 to every edge.
Undirected. Make your graph directed by replacing every edge with two directed edges, one going each way.

Related

Finding all independent connections in graph

I have an undirected graph. Is there any efficient algorithm on how to find all independent connections between two nodes? By independent, I mean that these connections could have common nodes but cannot have common edges.
In this example, there are 2 independent connections from 0 to 8 (0-2-3-4-8 or 0-5-6-7-8). I tried using Breadth-first search algorithm continuously while "pseudo-erasing" edges which I've already seen. Problem is that I can go through graph this way: 0-5-4-8 which is not right because I can't make any other path.
Thanks for any help!
What you are interested is to solve min cut problem between a source and sink (the first of the nodes of interest for you is a source and the second is a sink).
Here you can read about the approach to this task. Basically I link to a theorem proving that the max flow between the source and the sink equals the min cut. You are interested in the min cut as this is exactly the minimum number of edges that need to be removed in order to get your source and sink disconnected.
If you run a Ford Fulkerson max flow algorithm you can reconstruct the different paths from the source to the sink considering which reverse edges have capacity after the algorithm is finished. One last note - Ford Fulkerson is classically described in directed graph. To make it work for your undirected case represent each edge as two separate directed edges facing opposite directions. All your initial capacities should be equal to 1.

Graphs - How to count the minimum number of "broken roads" necessary to go from v1 to v2?

Given a graph (undirected, no-weighted and all vertices are connected to eachother), I need to find the minimum number of "bad edges" I must visit to go from A to B. For example, if there's a graph with 5 vertices and the bad edges are: (0,1), (0,2), (0,3) and (0,4), to go from 0 to 4 I'll need to visit at least 1 bad edge. It could be straightfoward from 0 to 4 or from 0 to 1 and then 1 to 4. The length of the path doesn't matter at all. I'm trying a modified BFS to do the job but I'm not quite sure if this is the right way. My modification is instead of using a queue, use a list and when I find a bad edge, I put it into the back of the list, so I'll only visit this edge if really necessary, but found out that it won't minimize the number of bad edges. Any advices?
While it can indeed be solved by weighted shortest path, there is actually a more efficient (in terms of run time solutions).
First, define an auxillary graph G'=(V,E') where e is in E' iff e is "good". This step is linear in the size of the graph.
Now, you can find connected components in G' using DFS or BFS in O(|V|+|E|).
Next, all you have to do is "collapse" all nodes to a single node that represent them (this is also linear time), and add the "bad edges" (note that there is never a "good edge" that connects between two components, or they would have been in the same component).
Now, you can run BFS on the new graph, and the length of the path is the minimal number of nodes needed.
While this is significantly more complex to implement than a simple weighted shortest path, this solution offers O(|V|+|E|) (which in your graph is O(|E|)) run time, compared to O(|E|log|V|) of weighted shortest path.

Tricky algorithm for finding alternative route in graph with few added edges

Okay, so I found this a bit tricky.
Basically, you have a directed graph (let's call it the base graph), that has some leaves and a node with 0 indegree that is called root. It may contain cycles.
From that base graph, a tree has been made, that contains the root and all leaves, and some connection between them. The nodes and edges that are not needed to connect the root to the leaves are left out.
Now imagine one or more edges in the tree "break", and can no longer be used. The problem now is to
a) If possible, find an alternative route(s) to the disconnected node(s), introducing as few previously unused edges from the base graph as possible.
b) If not possible, select which edges to "repair", repairing as few edges as possible to get all leaves connected again.
This is supposed to represent an electrical grid, and the breaks are power outages.
If just one edge is broken, it is easy enough. But say you have a graph with 100 leaves, 500 edges, and 50 edges break. Now to find which combination of adding previously unused edges from the base graph, and if necessary repairing some edges, to connect all leaves, seems like a very hard problem.
I imagined one could do some sort of brute force, where ALL combinations of unused edges, from using 1 to all of them, are tested. Or if repairs are needed, testing ALL combinations of repairs with all combinations of new edges. When the amount of edges get high, this seems to me very very inefficient.
My question is, does anyone have any smart ideas to how this could be done in a more efficient way? I hope I explained it well enough.
This is an NP-hard problem, and I'll explain why. Imagine that you have three layers of nodes: the root node, a layer of intermediate connecting nodes, and then a layer of leaf nodes. Edges go from root to intermediate nodes, and from an intermediate node to some subset of leaf nodes. Suppose you have some choice of intermediate nodes and edges to leaf nodes that gives you a connected tree graph, where each intermediate node has an edge to only one leaf node. Now imagine all edges in the reduced graph are removed. Then to find the minimum number of edges needed to add to repair the graph, this is equivalent to finding the minimum number of remaining intermediate nodes whose edges cover all of the leaf nodes. This is equivalent to the set cover problem for the leaf nodes http://en.wikipedia.org/wiki/Set_cover_problem and is NP-hard. Thus there is almost certainly no fast algorithm for your problem in the worst case (unless P = NP). Maybe if you bound the number of edges that are removed, you can come up with a polynomial time algorithm where the exponent in the polynomial depends (hopefully weakly) on how many edges were removed.
Seems like the start to a good efficient heuristic/solution would be to weight the edges. A couple simple approaches (not the most space efficient) as to how you could weight the edges based on the total number of edges are listed below.
If using any number of undamaged edges is better than using a single alternative edge and using any number of alternative edges is better than a single damaged edge.
Undamaged edge: 1
Alternative edge: E
Damaged edge: E^2
In the case of 100 vertices and 500 edges, alternative edges would be weighted as 500, while damaged edges would be weighted as 250000.
If using any number of undamaged edges is better than using a single alternative edge or a single damaged edge.
Undamaged edge: 1
Alternative/damaged edge: E
In the case of 100 vertices and 500 edges, alternative/damaged edges would be weighted as 500.
It seems like you then try a number of approaches to find either the exact solution or a heuristic result. The main suggestion I have for an algorithm is below.
Find the directed minimium spanning tree. If you use the weighting listed above, then I believe the result is optimum if I'm understanding things correctly.
Although, if you have intermediate nodes (nodes that are neither the root or a leaf), then this is likely to result in an overestimating heuristic. In which case, you might be able to get around it by running all pairs all shortest paths first and use the path costs for that as input for the directed minimium spanning tree algorithm, but that's probably a heuristic as well.

How to detect if the given graph has a cycle containing all of its nodes? Does the suggested algorithm have any flaws?

I have a connected, non-directed, graph with N nodes and 2N-3 edges. You can consider the graph as it is built onto an existing initial graph, which has 3 nodes and 3 edges. Every node added onto the graph and has 2 connections with the existing nodes in the graph. When all nodes are added to the graph (N-3 nodes added in total), the final graph is constructed.
Originally I'm asked, what is the maximum number of nodes in this graph that can be visited exactly once (except for the initial node), i.e., what is the maximum number of nodes contained in the largest Hamiltonian path of the given graph? (Okay, saying largest Hamiltonian path is not a valid phrase, but considering the question's nature, I need to find a max. number of nodes that are visited once and the trip ends at the initial node. I thought it can be considered as a sub-graph which is Hamiltonian, and consists max. number of nodes, thus largest possible Hamiltonian path).
Since i'm not asked to find a path, I should check if a hamiltonian path exists for given number of nodes first. I know that planar graphs and cycle graphs (Cn) are hamiltonian graphs (I also know Ore's theorem for Hamiltonian graphs, but the graph I will be working on will not be a dense graph with a great probability, thus making Ore's theorem pretty much useless in my case). Therefore I need to find an algorithm for checking if the graph is cycle graph, i.e. does there exist a cycle which contains all the nodes of the given graph.
Since DFS is used for detecting cycles, I thought some minor manipulation to the DFS can help me detect what I am looking for, as in keeping track of explored nodes, and finally checking if the last node visited has a connection to the initial node. Unfortunately
I could not succeed with that approach.
Another approach I tried was excluding a node, and then try to reach to its adjacent node starting from its other adjacent node. That algorithm may not give correct results according to the chosen adjacent nodes.
I'm pretty much stuck here. Can you help me think of another algorithm to tell me if the graph is a cycle graph?
Edit
I realized by the help of the comment (thank you for it n.m.):
A cycle graph consists of a single cycle and has N edges and N vertices. If there exist a cycle which contains all the nodes of the given graph, that's a Hamiltonian cycle. – n.m.
that I am actually searching for a Hamiltonian path, which I did not intend to do so:)
On a second thought, I think checking the Hamiltonian property of the graph while building it will be more efficient, which is I'm also looking for: time efficiency.
After some thinking, I thought whatever the number of nodes will be, the graph seems to be Hamiltonian due to node addition criteria. The problem is I can't be sure and I can't prove it. Does adding nodes in that fashion, i.e. adding new nodes with 2 edges which connect the added node to the existing nodes, alter the Hamiltonian property of the graph? If it doesn't alter the Hamiltonian property, how so? If it does alter, again, how so? Thanks.
EDIT #2
I, again, realized that building the graph the way I described might alter the Hamiltonian property. Consider an input given as follows:
1 3
2 3
1 5
1 3
these input says that 4th node is connected to node 1 and node 3, 5th to node 2 and node 3 . . .
4th and 7th node are connected to the same nodes, thus lowering the maximum number of nodes that can be visited exactly once, by 1. If i detect these collisions (NOT including an input such as 3 3, which is an example that you suggested since the problem states that the newly added edges are connected to 2 other nodes) and lower the maximum number of nodes, starting from N, I believe I can get the right result.
See, I do not choose the connections, they are given to me and I have to find the max. number of nodes.
I think counting the same connections while building the graph and subtracting the number of same connections from N will give the right result? Can you confirm this or is there a flaw with this algorithm?
What we have in this problem is a connected, non-directed graph with N nodes and 2N-3 edges. Consider the graph given below,
A
/ \
B _ C
( )
D
The Graph does not have a Hamiltonian Cycle. But the Graph is constructed conforming to your rules of adding nodes. So searching for a Hamiltonian Cycle may not give you the solution. More over even if it is possible Hamiltonian Cycle detection is an NP-Complete problem with O(2N) complexity. So the approach may not be ideal.
What I suggest is to use a modified version of Floyd's Cycle Finding algorithm (Also called the Tortoise and Hare Algorithm).
The modified algorithm is,
1. Initialize a List CYC_LIST to ∅.
2. Add the root node to the list CYC_LIST and set it as unvisited.
3. Call the function Floyd() twice with the unvisited node in the list CYC_LIST for each of the two edges. Mark the node as visited.
4. Add all the previously unvisited vertices traversed by the Tortoise pointer to the list CYC_LIST.
5. Repeat steps 3 and 4 until no more unvisited nodes remains in the list.
6. If the list CYC_LIST contains N nodes, then the Graph contains a Cycle involving all the nodes.
The algorithm calls Floyd's Cycle Finding Algorithm a maximum of 2N times. Floyd's Cycle Finding algorithm takes a linear time ( O(N) ). So the complexity of the modied algorithm is O(N2) which is much better than the exponential time taken by the Hamiltonian Cycle based approach.
One possible problem with this approach is that it will detect closed paths along with cycles unless stricter checking criteria are implemented.
Reply to Edit #2
Consider the Graph given below,
A------------\
/ \ \
B _ C \
|\ /| \
| D | F
\ / /
\ / /
E------------/
According to your algorithm this graph does not have a cycle containing all the nodes.
But there is a cycle in this graph containing all the nodes.
A-B-D-C-E-F-A
So I think there is some flaw with your approach. But suppose if your algorithm is correct, it is far better than my approach. Since mine takes O(n2) time, where as yours takes just O(n).
To add some clarification to this thread: finding a Hamiltonian Cycle is NP-complete, which implies that finding a longest cycle is also NP-complete because if we can find a longest cycle in any graph, we can find the Hamiltonian cycle of the subgraph induced by the vertices that lie on that cycle. (See also for example this paper regarding the longest cycle problem)
We can't use Dirac's criterion here: Dirac only tells us minimum degree >= n/2 -> Hamiltonian Cycle, that is the implication in the opposite direction of what we would need. The other way around is definitely wrong: take a cycle over n vertices, every vertex in it has exactly degree 2, no matter the size of the circle, but it has (is) an HC. What you can tell from Dirac is that no Hamiltonian Cycle -> minimum degree < n/2, which is of no use here since we don't know whether our graph has an HC or not, so we can't use the implication (nevertheless every graph we construct according to what OP described will have a vertex of degree 2, namely the last vertex added to the graph, so for arbitrary n, we have minimum degree 2).
The problem is that you can construct both graphs of arbitrary size that have an HC and graphs of arbitrary size that do not have an HC. For the first part: if the original triangle is A,B,C and the vertices added are numbered 1 to k, then connect the 1st added vertex to A and C and the k+1-th vertex to A and the k-th vertex for all k >= 1. The cycle is A,B,C,1,2,...,k,A. For the second part, connect both vertices 1 and 2 to A and B; that graph does not have an HC.
What is also important to note is that the property of having an HC can change from one vertex to the other during construction. You can both create and destroy the HC property when you add a vertex, so you would have to check for it every time you add a vertex. A simple example: take the graph after the 1st vertex was added, and add a second vertex along with edges to the same two vertices of the triangle that the 1st vertex was connected to. This constructs from a graph with an HC a graph without an HC. The other way around: add now a 3rd vertex and connect it to 1 and 2; this builds from a graph without an HC a graph with an HC.
Storing the last known HC during construction doesn't really help you because it may change completely. You could have an HC after the 20th vertex was added, then not have one for k in [21,2000], and have one again for the 2001st vertex added. Most likely the HC you had on 23 vertices will not help you a lot.
If you want to figure out how to solve this problem efficiently, you'll have to find criteria that work for all your graphs that can be checked for efficiently. Otherwise, your problem doesn't appear to me to be simpler than the Hamiltonian Cycle problem is in the general case, so you might be able to adjust one of the algorithms used for that problem to your variant of it.
Below I have added three extra nodes (3,4,5) in the original graph and it does seem like I can keep adding new nodes indefinitely while keeping the property of Hamiltonian cycle. For the below graph the cycle would be 0-1-3-5-4-2-0
1---3---5
/ \ / \ /
0---2---4
As there were no extra restrictions about how you can add a new node with two edges, I think by construction you can have a graph that holds the property of hamiltonian cycle.

Shortest path in absence of the given edge

Suppose we are given a weighted graph G(V,E).
The graph contains N vertices (Numbered from 0 to N-1) and M Bidirectional edges .
Each edge(vi,vj) has postive distance d (ie the distance between the two vertex vivj is d)
There is atmost one edge between any two vertex and also there is no self loop (ie.no edge connect a vertex to
itself.)
Also we are given S the source vertex and D the destination vertex.
let Q be the number of queries,each queries contains one edge e(x,y).
For each query,We have to find the shortest path from the source S to Destination D, assuming that edge (x,y) is absent in original graph.
If no any path exists from S to D ,then we have to print No.
Constraints are high 0<=(N,Q,M)<=25000
How to solve this problem efficiently?
Till now what i did is implemented the simple Dijakstra algorithm.
For each Query Q ,everytime i am assigning (x,y) to Infinity
and finding Dijakstra shortest path.
But this approach will be very slow as overall complexity will be Q(time complexity of Dijastra Shortes path)*
Example::
N=6,M=9
S=0 ,D=5
(u,v,cost(u,v))
0 2 4
3 5 8
3 4 1
2 3 1
0 1 1
4 5 1
2 4 5
1 2 1
1 3 3
Total Queries =6
Query edge=(0,1) Answer=7
Query edge=(0,2) Answer=5
Query edge=(1,3) Answer=5
Query edge=(2,3) Answer=6
Query edge=(4,5) Answer=11
Query edge=(3,4) Answer=8
First, compute the shortest path tree from source node to destination.
Second, loop over all the queries and cut the shortest path at the edge specified by the query; this defines a min-cut problem, where you have the distance between the source node and the frontier of one partition and the frontier of the another and the destination; you can compute this problem very easily, at most O(|E|).
Thus, this algorithm requires O(Q|E| + |V|log|V|), asymptotically faster than the naïve solution when |V|log|V| > |E|.
This solution reuses Dijkstra's computation, but still processes each query individually, so perhaps there are room to improvements by exploiting the work did in a previous query in successive queries by observing the shape of the cut induced by the edge.
For each query the graph changes only very slightly, so you can reuse a lot of your computation.
I suggest the following approach:
Compute the shortest path from S to all other nodes (Dijkstras Algorithm does that for you already). This will give you a shortest path tree T.
For each query, take this tree, pruned by the edge (x,y) from the query. This might be the original tree (if (x,y) was no where on the tree) or a smaller tree T'.
If D is in the T', you can take the original shortest path
Otherwise start Dijkstra, but use the labels you already have from the T' (these paths are already smallest) as permanent labels.
If you run the Dijkstra in step 2 you can reuse the pruned of part of tree T in the following way: Every time you want to mark a node permanent (which is one of the nodes not in T') you may attach the entire subtree of this node (from the original tree T) to your new shortest path tree and label all its nodes permanent.
This way you reuse as much information as possible from the first shortest path run.
In your example this would mean:
Compute shortest path tree:
0->1->2->3->4->5
(in this case a very simple)
Now assume we get query (1,2).
We prune edge (1,2) leaving us with
0->1
From there we start Dijkstra getting 2 and 3 as next permanent marked nodes.
We connect 1 to 2 and 1 to 3 in the new shortest path tree and attach the old subtree from 3:
2<-0->1->3->4->5
So we got the shortest path with just running one additional step of Dijkstras Algorithm.
The correctness of the algorithm follows from all paths in tree T being at most as long as in the new Graph from the Query (where every shortest path can only be longer). Therefore we can reuse every path from the tree that is still feasible (i.e. where no edge was removed).
If performance matters a lot, you can improve on the Dijkstra performance through a lot of implementation tricks. A good entry point for this might be the DIMACS Shortest Path Implementation Challenge.
One simple optimization: first run Dijkstra on complete graph (with no edges removed).
Then, for each query - check if the requested edge belongs to that shortest path. If not - removing this edge won't make any difference.

Resources