Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Graph
  • Practice Graph
  • MCQs on Graph
  • Graph Tutorial
  • Graph Representation
  • Graph Properties
  • Types of Graphs
  • Graph Applications
  • BFS on Graph
  • DFS on Graph
  • Graph VS Tree
  • Transpose Graph
  • Dijkstra's Algorithm
  • Minimum Spanning Tree
  • Prim’s Algorithm
  • Topological Sorting
  • Floyd Warshall Algorithm
  • Strongly Connected Components
  • Advantages & Disadvantages
Open In App
Next Article:
Shortest Path in Directed Acyclic Graph
Next article icon

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
Shortest Path in Directed Acyclic Graph
author
abhishek9202
Improve
Article Tags :
  • Graph
  • Competitive Programming
  • DSA
  • CSES Problems
Practice Tags :
  • Graph

Similar Reads

  • CSES Solutions – Reachable Nodes
    A directed acyclic graph consists of n nodes and m edges. The nodes are numbered 1,2,…,n. Calculate for each node the number of nodes you can reach from that node (including the node itself). Examples: Input: n = 5, m = 6, edges = {{1, 2}, {1, 3}, {1, 4}, {2, 3}, {3, 5}, {4, 5}}Output: 5 3 2 2 1Expl
    8 min read
  • CSES Solutions - Even Outdegree Edges
    Given an undirected graph, your task is to choose a direction for each edge so that in the resulting directed graph's each node has an even outdegree. The outdegree of a node is the number of edges coming out of that node. Examples: Input: N = 4, M = 4, Edges = {{1, 3}, {3, 2}, {3, 4}, {1, 4}}Output
    4 min read
  • Shortest Path in Directed Acyclic Graph
    Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices. Recommended PracticeShortest path from 1 to nTry It! For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–
    15 min read
  • Longest Path in a Directed Acyclic Graph
    Given a Weighted Directed Acyclic Graph (DAG) and a source vertex s in it, find the longest distances from s to all other vertices in the given graph. The longest path problem for a general graph is not as easy as the shortest path problem because the longest path problem doesn’t have optimal substr
    15+ min read
  • Edge Coloring of a Graph
    In graph theory, edge coloring of a graph is an assignment of "colors" to the edges of the graph so that no two adjacent edges have the same color with an optimal number of colors. Two edges are said to be adjacent if they are connected to the same vertex. There is no known polynomial time algorithm
    9 min read
  • Clone a Directed Acyclic Graph
    A directed acyclic graph (DAG) is a graph which doesn't contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ |
    12 min read
  • CSES Solutions – Cycle Finding
    Given a directed graph with N nodes and M edges determine if there exists a negative cycle in the graph. If a negative cycle exists print "YES" and output any vertex sequence that forms the cycle; otherwise print "NO". Examples: Input: 4 5 1 2 1 2 4 1 3 1 1 4 1 -3 4 3 -2 Output: YES 1 2 4 1 Approach
    11 min read
  • Detect Cycle in Graph using DSU
    Given an undirected graph, the task is to check if the graph contains a cycle or not, using DSU. Examples: Input: The following is the graph Output: YesExplanation: There is a cycle of vertices {0, 1, 2}. Recommended PracticeDetect Cycle using DSUTry It!We already have discussed an algorithm to dete
    13 min read
  • Euler Circuit in a Directed Graph
    Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. A graph is said to be eulerian if it has a eulerian cycle. We have discussed eulerian circuit for an undirected graph. In this post, the same is discus
    13 min read
  • Graph Cycle Detection in C++
    Detecting cycles in a graph is a crucial problem in graph theory that has various applications in fields like network analysis, databases, compilers, and many others. In this article, we will learn how to detect cycles in a graph in C++. Graph Cycle Detection in C++A cycle in a graph is a path that
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences