Given a directed and strongly connected graph with non-negative edge weights. We define the mean weight of a cycle as the summation of all the edge weights of the cycle divided by the no. of edges. Our task is to find the minimum mean weight among all the directed cycles of the graph.
Input : Below Graph
Output : 1.66667
Method to find the smallest mean weight value cycle efficiently
Step 1: Choose first vertex as source.
Step 2: Compute the shortest path to all other vertices
on a path consisting of k edges 0 <= k <= V
where V is number of vertices.
This is a simple dp problem which can be computed
by the recursive solution
dp[k][v] = min(dp[k][v], dp[k-1][u] + weight(u,v)
where v is the destination and the edge(u,v) should
belong to E
Step 3: For each vertex calculate max(dp[n][v]-dp[k][v])/(n-k)
Step 4: The minimum of the values calculated above is the
Please refer to the solution of problem 9.2 here for proof that the above steps find minimum average weight.
Here the graph with no cycle will return value as -1.
Time Complexity : The time complexity of the given program is O(V^3), where V is the number of vertices in the graph. This is because the program uses a nested loop to fill up the dp table, and the size of the dp table is V^2. The outermost loop runs V times, the middle loop runs V times, and the innermost loop can run up to V times in the worst case, giving a total time complexity of O(V^3). The other parts of the program have a lower time complexity and do not contribute significantly to the overall time complexity.
Space Complexity : The space complexity of the given program is O(V^2), where V is the number of vertices in the graph. This is because the program creates a 2D array dp of size (V+1)xV, which requires O(V^2) space. Additionally, the program creates a vector of edges, which takes up O(E) space, where E is the number of edges in the graph. However, in this particular implementation, the number of edges is not directly stored, and it is not clear whether all edges are actually added to the vector. Therefore, the space complexity is mainly determined by the size of the dp array, which is O(V^2).
This article is contributed by Ayush Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...