A DAG is given to us, we need to find maximum number of edges that can be added to this DAG, after which new graph still remain a DAG that means the reformed graph should have maximal number of edges, adding even single edge will create a cycle in graph.
The Output for above example should be following edges in any order. 4-2, 4-5, 4-3, 5-3, 5-1, 2-0, 2-1, 0-3, 0-1
As shown in above example, we have added all the edges in one direction only to save ourselves from making a cycle. This is the trick to solve this question. We sort all our nodes in topological order and create edges from node to all nodes to the right if not there already.
How can we say that, it is not possible to add any more edge? the reason is we have added all possible edges from left to right and if we want to add more edge we need to make that from right to left, but adding edge from right to left we surely create a cycle because its counter part left to right edge is already been added to graph and creating cycle is not what we needed.
So solution proceeds as follows, we consider the nodes in topological order and if any edge is not there from left to right, we will create it.
Below is the solution, we have printed all the edges that can be added to given DAG without making any cycle.
4-5, 4-2, 4-3, 5-3, 5-1, 2-0, 2-1, 0-3, 0-1
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Assign directions to edges so that the directed graph remains acyclic
- Minimum edges to be added in a directed graph so that any node can be reachable from a given node
- Maximum number of edges in Bipartite graph
- Maximum number of edges among all connected components of an undirected graph
- Ways to Remove Edges from a Complete Graph to make Odd Edges
- Dijkstra's shortest path with minimum edges
- All vertex pairs connected with exactly k edges in a graph
- Right sibling of each node in a tree given as array of edges
- Minimum number of edges between two vertices of a Graph
- Minimum number of edges between two vertices of a graph using DFS
- Number of Simple Graph with N Vertices and M Edges
- Count number of edges in an undirected graph
- Count all possible walks from a source to a destination with exactly k edges
- Remove all outgoing edges except edge with minimum weight