Open In App

CSES Solutions - Acyclic Graph Edges

Last Updated : 25 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an undirected graph, the task is to choose a direction for each edge so that the resulting directed graph is acyclic. You can print any valid solution.

Example:

Input: n = 3, m = 3, edge = {{1, 2}, {2, 3}, {3, 1}}
Output:
1 2
2 3
1 3
Explanation: Connecting the graph in this manner will result in directed acyclic graph.

Input: n = 4, m = 4, edge = {{1, 2}, {2, 3}, {3, 4}, {4, 1}}

Output:
1 2
2 3
3 4
1 4

Explanation: Connecting the graph in this manner will result in directed acyclic graph.

Approach: To solve the problem, follow the idea below:

The idea is to direct the edges from smaller vertex to largest one, to make the graph acyclic. It ensures that all edges are directed in a way that prevents cycles. Since each edge is directed from a smaller node to a larger node, it’s impossible to go back to a smaller node from a larger node, which prevents any cycles from forming.

Step-by-step algorithm:

  • Loop through each edge.
  • For each edge, check if the first vertex is greater than the second vertex.
  • If so, swap the vertices to ensure the edge is directed from the smaller vertex to the larger vertex.

Below is the implementation of the algorithm:

C++
// C++ code
#include <bits/stdc++.h>
using namespace std;

vector<pair<int, int> >
diracycgraph(vector<pair<int, int> >& edge, int m)
{
    // Direct all the edges from smaller vertex to larger
    // one
    for (int i = 0; i < m; i++)
        if (edge[i].first > edge[i].second)
            swap(edge[i].first, edge[i].second);
    return edge;
}

// Driver code
int main()
{
    int n = 3, m = 3;
    vector<pair<int, int> > edge{ { 1, 2 },
                                  { 2, 3 },
                                  { 3, 1 } };

    vector<pair<int, int> > res = diracycgraph(edge, m);
    for (int i = 0; i < m; i++)
        cout << res[i].first << " " << res[i].second
             << endl;
}

Output
1 2
2 3
1 3

Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(1)


Next Article
Practice Tags :

Similar Reads