Total cycles in a Undirected graph - algorithm

Given an undirected graph with N vertices and M edges I need to find the number of cycles in the graph. But there is a constraint.
Here is an example of it:
Consider this graph with 6 vertices and 7 edge pairs :- A-B , B-C , C-F , A-D , D-E , E-F , B-E.
Here is the image for better understanding :
Then here 2 cycles should be counted that are A-B-E-D-A and B-C-F-E-B but not A-B-C-F-E-D-A
So I need to find the count of the total cycles in the graph.

I think you are looking for a cycle basis of your graph. You do that by finding any spanning tree of the graph (for example a DFS or BFS tree). The non-tree edges of the graph represent a cycle basis: If you connect the endpoints by the unique path through the tree, you get an element of the basis.
So if the graph is connected, the number of basis elements is m - n + 1 (m = number of edges, n = number of nodes). If it's not connected, just decompose it into connected components and sum up the number of basis elements of the components. You get something like m - n + c where c is the number of connected components. Thus, if you're not interested in the actual cycles and only in their count, you just need to find the number of connected components. You can use DFS or BFS for that as well.

Related

An undirected graph having n edges, then find out no. of vertices that graph have?

An undirected graph having 'n' number of edges, then find out number of vertices that graph have?‏‏‎
Since an edge is a connection between to vertices, the amount of vertices is at max 2n.
The amount of vertices is at minimum n+1. (This is pretty logical if you imagine that you have 2 edges - then you will at minimum have 3 vertices, because each edge must connect 2 vertices)
So if e = n, then n+1 <= v <= 2n
There is no exact formula for the number of vertices in terms of number of edges in the general case. However, if you take special cases, you can say more: if the graph is a tree, then the number of vertices is one more than the number of edges.

Give minimum permutation weight for edges such that a given set of edge is the Minimum Spanning Tree

Question:
Given a graph of N nodes and M edges, the edges are indexed from 1 -> M. It is guaranteed that there's a path between any 2 nodes.
You need to assign weights for M edges. The weights are in the range of [1...M], and each number can only occur once.
To be shorted, the answer should be a permutation array of [1...M], in which arr[i] = x means edge[i] has the weight of x.
You are given a set R of n-1 edges. R is guaranteed to be a Spanning Tree of the graph.
Find a way to assign weights so that R is the Minimum Spanning Tree of the graph, if there are multiple answers, print the one with minimum lexicographical order.
Contraints:
N, M <= 10^6
Example:
Edges:
3 4
1 2
2 3
1 3
1 4
R = [2, 4, 5]
Answer: 3 4 5 1 2
Explaination:
If you assign weights for the graph like the above image, the MST would be the set R, and it has the smallest lexicographical order.
My take with O(N^2):
Since it asks for the minimum lexicographical order, I traverse through the list of edges, assigning the weights in an increasing order. Intially, w = 1. There can be 3 situations:
If edge[i] is in R, assign weight[i] = w, increase w by 1
If edge[i] is not in R: say edge[i] connect nodes u and v. assign weight and increase w for each edge in the path from u to v in R (if that edge is not assigned yet). Then assign weight and increase w for edge[i]
If edge[i] is assigned, skip it
Is there any way to improve my solution so that it can work in O(N.logN) or less?
Yes, there's an O(m log m)-time algorithm.
The fundamental cycle of a non-tree edge e is comprised of e and the path in the tree between the endpoints of e. Given weights, the spanning tree is minimum if and only if, for every non-tree edge e, the heaviest edge in the fundamental cycle of e is e itself.
The lexicographic objective lends itself to a greedy algorithm, where we find the least valid assignment for edge 1, then edge 2 given edge 1, then edge 3 given the previous edges, etc. Here's the core idea: if the next unassigned edge is a non-tree edge, assign the next numbers to the unassigned tree edges in its fundamental cycle; then assign the next number.
In the example, edge 3-4 is first, and edges 1-3 and 1-4 complete its fundamental cycle. Therefore we assign 1-3 → 1 and 1-4 → 2 and then 3-4 → 3. Next is 1-2, a tree edge, so 1-2 → 4. Finally, 2-3 → 5 (1-2 and 1-3 are already assigned).
To implement this efficiently, we need two ingredients: a way to enumerate the unassigned edges in a fundamental cycle, and a way to assign numbers. My proposal for the former would be to store the spanning tree with the assigned edges contracted. We don't need anything fancy; start by rooting the spanning tree somewhere and running depth-first search to record parent pointers and depths. The fundamental cycle of e will be given by the paths to the least common ancestor of the endpoints of e. To do the contraction, we add a Boolean field indicating whether the parent edge is contracted, then use the path compression trick from disjoint-set forests. The work will be O(m log m) worst case, but O(m) average case. I think there's a strong possibility that the offline least common ancestor algorithms can be plugged in here to get the worst case down to O(m).
As for number assignment, we can handle this in linear time. For each edge, record the index of the edge that caused it to be assigned. At the end, stably bucket sort by this index, breaking ties by putting tree edges before non-tree. This can be done in O(m) time.

Minimum Hop Count in Directed Graph based on Conditional Statement

A directed graph G is given with Vertices V and Edges E, representing train stations and unidirectional train routes respectively.
Trains of different train numbers move in between pairs of Vertices in a single direction.
Vertices of G are connected with one another through trains with allotted train numbers.
A hop is defined when a passenger needs to shift trains while moving through the graph. The passenger needs to shift trains only if the train-number changes.
Given two Vertices V1 and V2, how would one go about calculating the minimum number of hops needed to reach V2 starting from V1?
In the above example, the minimum number of hops between Vertices 0 and 3 is 1.
There are two paths from 0 to 3, these are
0 -> 1 -> 2 -> 7-> 3
Hop Count 4
Hop Count is 4 as the passenger has to shift from Train A to B then C and B again.
and
0 -> 5 -> 6 -> 8 -> 7 -> 3
Hop Count 1
Hop Count is 1 as the passenger needs only one train route, B to get from Vertices 0 to 3
Thus the minimum hop count is 1.
Input Examples
Input Graph Creation
Input To be solved
Output Example
Output - Solved with Hop Counts
0 in the Hop Count column implies that the destination can't be reached
Assuming number of different trainIDs is relatively small (like 4 in your example), then I suggest using layered graph approach.
Let number of vertices be N, number of edges M, and number of different trainIDs K.
Let's divide our graph to K graphs. (graphA, graphB, ...)
graphA contains only edges labeled with A, and so on.
Weight of each edge in each of the graphs is 0.
Now create edges between these graphs.
Edge between graphs is representing a 'hop'
grapha[i] connects to graphB[i], graphC[i], ...
Each of these edges has weight 1.
Now for every graph run Dijkstra's shortest path algorithm from V1 in that graph, and read results from V2 in all graphs, take minimal value.
This way minimum of results for running dijkstra's for every graph will be your minimum number of hops.
Memory complexity is O(K*(N+M))
And time complexity is O(K*(((2^K)*N+M)*log(KV)))
(2^K)*N comes from fact that for every 1<=i<=N, vertices graphA[i],graphB[i],... must be connected to each other, and this gives 2^K connections for every i, and (2^K)*N connections in total.
For cases where K is relatively small, like 4 in your example, but N and M are quite big, this algorithm works like a charm. It isn't suitable for situation where K is big though.
I'm not sure if that's clear. Tell me if you need more detailed explanation.
EDIT:
Hope this makes my algorithm more clear.
Black edges have weight 0, and red edges have weight 1.
By using layered graph approach, we translated our special graph into plain weighted graph, so we can just run Dijkstra's algorithm on it.
Sorry for ugly image.
EDIT:
Since max K = 10, we would like to remove 2^K from our time complexity. I believe this can be done by making edges that represent possible hops virtual, instead of physically storing them on adjacency list.

Disconnecting a connected graph

I need to find the minimum number of edges that need to be removed from a connected graph (which may have cycles and has unweighted undirected edges) so that i end up with two given nodes - A and B in separate disconnected parts.
Input: Edges, Node A, Node B. (There exists at least 1 path from A to B)
Output: Minimum number of edges to be removed so that there remains no path between A & B
I can only think of the worst solution:-
best = no. of edges in the given connected graph G
For each possible subset S of Edges in the given connected graph G
Graph temp = G minus edges S
if there exists a path between A and B in temp
continue
else
best = Min(best, no. of edges in S)
return best
I'm looking for a solution which would work comfortably for a graph with 15 vertices within a second or two.
I wonder if my solution is good enough.
Thanks!
P.s. I'm not sure whether the big O complexity of my solution is 2^n or n*(2^n) or (n^2)*(2^n). I think its the latter but I would like to know for sure.
You can use a maximum flow algorithm to compute the minimum cut between A and B in your graph.
Runtime: O(n*m) with an excess-scaling push-relabel variant (since you have only unit capacities).
Your solution is O(2^m * (n + m)) if you use DFS or BFS for reachability in the fixed subgraph.

Second min cost spanning tree

I'm writing an algorithm for finding the second min cost spanning tree. my idea was as follows:
Use kruskals to find lowest MST.
Delete the lowest cost edge of the MST.
Run kruskals again on the entire graph.
return the new MST.
My question is: Will this work? Is there a better way perhaps to do this?
You can do it in O(V2). First compute the MST using Prim's algorithm (can be done in O(V2)).
Compute max[u, v] = the cost of the maximum cost edge on the (unique) path from u to v in the MST. Can be done in O(V2).
Find an edge (u, v) that's NOT part of the MST that minimizes abs(max[u, v] - weight(u, v)). Can be done in O(E) == O(V2).
Return MST' = MST - {the edge that has max[u, v] weight} + {(u, v)}, which will give you the second best MST.
Here's a link to pseudocode and more detailed explanations.
Consider this case:
------100----
| |
A--1--B--3--C
| |
| 3
| |
2-----D
The MST consists of A-B-D-C (cost 6). The second min cost is A-B-C-D (cost 7). If you delete the lowest cost edge, you will get A-C-B-D (cost 105) instead.
So your idea will not work. I have no better idea though...
You can do this -- try removing the edges of the MST, one at a time from the graph, and run the MST, taking the min from it. So this is similar to yours, except for iterative:
Use Kruskals to find MST.
For each edge in MST:
Remove edge from graph
Calculate MST' on MST
Keep track of smallest MST
Add edge back to graph
Return the smallest MST.
This is similar to Larry's answer.
After finding MST,
For each new_edge =not a edge in MST
Add new_edge to MST.
Find the cycle that is formed.
Find the edge with maximum weight in
cycle that is not the non-MST edge
you added.
Record the weight increase as W_Inc
= w(new_edge) - w(max_weight_edge_in_cycle).
If W_Inc < Min_W_Inc_Seen_So_Far Then
Min_W_Inc_Seen_So_Far = W_Inc
edge_to_add = new_edge
edge_to_remove = max_weight_edge_in_cycle
Solution from following link.
http://web.mit.edu/6.263/www/quiz1-f05-sol.pdf
slight edit to your algo.
Use kruskals to find lowest MST.
for all edges i of MST
Delete edge i of the MST.
Run kruskals again on the entire graph.
loss=cost new edge introduced - cost of edge i
return MST for which loss is minimum
Here is an algorithm which compute the 2nd minimum spanning tree in O(n^2)
First find out the mimimum spanning tree (T). It will take O(n^2) without using heap.
Repeat for every edge e in T. =O(n^2)
Lets say current tree edge is e. This tree edge will divide the tree into two trees, lets say T1 and T-T1. e=(u,v) where u is in T1 and v is in T-T1. =O(n^2)
Repeat for every vertex v in T-T1. =O(n^2)
Select edge e'=(u,v) for all v in T-T1 and e' is in G (original graph) and it is minimum
Calculate the weight of newly formed tree. Lets say W=weight(T)-weight(e)+weight(e')
Select the one T1 which has a minimum weight
Your approach will not work, as it might be the case that min. weight edge in the MST is a bridge (only one edge connecting 2 parts of graph) so deleting this edge from the set will result in 2 new MST as compared to one MST.
based on #IVlad's answer
Detailed explanation of the O(V² log V) algorithm
Find the minimum spanning tree (MST) using Kruskal's (or Prim's) algorithm, save its total weight, and for every node in the MST store its tree neighbors (i.e. the parent and all children) -> O(V² log V)
Compute the maximum edge weight between any two vertices in the minimum spanning tree. Starting from every vertex in the MST, traverse the entire tree with a depth- or breadth-first search by using the tree node neighbor lists computed earlier and store the maximum edge weight encountered so far at every new vertex visited. -> O(V²)
Find the second minimum spanning tree and its total weight. For every edge not belonging to the original MST, try disconnecting the two vertices it connects by removing the tree edge with the maximum weight in between the two vertices, and then reconnecting them with the currently considered vertex (note: the MST should be restored to its original state after every iteration). The total weight can be calculated by subtracting the weight of the removed edge and adding that of the added one. Store the minimum of the total weights obtained.
To practice you could try the competitive programming problem UVa 10600 - ACM Contest and Blackout, which involves finding the second minimum spanning tree in a weighted graph, as asked by the OP. My implementation (in modern C++) can be found here.
MST is a tree which has the minimum weight total of all edges of the graph. Thus, 2nd minimum mst will have the 2nd minimum total weight of all edges in the graph.
let T -> BEST_MST ( sort the edges in the graph , then find MST using kruskal algorithm)
T ' -> 2nd best MST
let's say T has 7 edges , now to find T ' we will one by one remove one of those 7 edges and find a replacement for that edge ( cost of that edge definitely will be greater than the edge we just removed from T ).
let's say original graph has 15 edges
our best MST ( T ) has 7 edges
and 2nd best MST ( T ' ) will also going to have 7 edges only
How to find T '
there are 7 edges in T , now for all those 7 edges remove them one by one and find replacement for those edges .
let's say edges in MST ( T ) --> { a,b,c,d,e,f,g }
let's say our answer will be 2nd_BEST_MST and initially it has infinte value ( i know it doesn't sounds good , let's just assume it for now ).
for all edges in BEST_MST :
current_edge = i
find replacement for that edge, replacement for that edge will definitely going to have have weight more than the ith edge ( one of 7 edges )
how we will going to find the replacement for that edge , using Kruskul algorithm ( we are finding the MST again , so we will use kruskal algorithm only , but this we don't have to sort edges again , because we did it when we were finding the BEST_MST ( T ).
NEW_MST will be generated
2nd_best_MST = min( NEW_MST , 2nd_best_MST )
return 2nd_best_MST
ALGORITHM
let' say orignal graph has 10 edges
find the BEST_MST ( using kruskal algo) and assume BEST_MST has only 6 edges
bow there are 4 edges remaining which is not in the BEST_MST ( because their weight value is large and one of those edges will give us our 2nd_Best_MST
for each edge 'X' not present in the BEST_MST ( i.e. 4 edges left ) add that edge in out BEST_MST which will create the cycle
find the edge 'K' with the maximum weight in the cycle ( other than newly_added_edge 'X' )
remove edge 'K' temporarily which will form a new spanning tree
calculate the difference in weight and map the weight_difference with the edge 'X' .
repeat step 4 for all those 4 edges and return the spanning tree with the smallest weight difference to the BEST_MST.

Resources