{"id":34272,"date":"2024-11-01T09:26:16","date_gmt":"2024-11-01T09:26:16","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=34272"},"modified":"2024-11-01T10:57:54","modified_gmt":"2024-11-01T10:57:54","slug":"c-coding-test-course-topological-sorting-2","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/34272\/","title":{"rendered":"C++ Coding Test Course, Topological Sorting"},"content":{"rendered":"<p><body><\/p>\n<p>Hello! In this article, we will learn about <strong>topological sorting<\/strong>. Topological sorting is an algorithm for linearly arranging the vertices in a directed acyclic graph (DAG), which is useful when a specific order needs to be maintained. For example, it is used when handling task dependencies or for compilers to determine the execution order of code.<\/p>\n<h2>Problem Description<\/h2>\n<p>Let&#8217;s solve the following problem.<\/p>\n<div class=\"example\">\n<h3>Problem: Task Scheduling<\/h3>\n<p>Given multiple tasks, each task requires specific prerequisite tasks. You can only perform the task after all its prerequisite tasks have been completed. The vertices of the graph represent tasks, and the edges represent the prerequisites. List the given tasks in a possible order.<\/p>\n<\/div>\n<h2>Input<\/h2>\n<p>The first line contains the number of vertices <code>N<\/code> (1 \u2264 N \u2264 1000) and the number of edges <code>M<\/code> (0 \u2264 M \u2264 10000).<\/p>\n<p>The next <code>M<\/code> lines contain pairs of <code>x<\/code> <code>y<\/code>, which means that task <code>x<\/code> must be performed before task <code>y<\/code>.<\/p>\n<h2>Output<\/h2>\n<p>Print the order in which the tasks can be performed, separated by spaces in a single line. If the order is not possible, print <code>-1<\/code>.<\/p>\n<h2>Example Input<\/h2>\n<pre>\n    6 6\n    1 2\n    1 3\n    2 4\n    3 4\n    4 5\n    5 6\n    <\/pre>\n<h2>Example Output<\/h2>\n<pre>1 2 3 4 5 6<\/pre>\n<h2>Principle of Topological Sorting<\/h2>\n<p>Topological sorting can be implemented using two methods: <strong>DFS (Depth First Search)<\/strong> and <strong>BFS (Breadth First Search)<\/strong>. Here, we will introduce Kahn&#8217;s algorithm using BFS. Kahn&#8217;s algorithm proceeds as follows.<\/p>\n<ol>\n<li>Record the in-degree of all vertices.<\/li>\n<li>Add the vertices with in-degree 0 to a queue.<\/li>\n<li>Remove one vertex from the queue at a time and add it to the result list.<\/li>\n<li>Remove all the edges going out from the removed vertex and update the in-degree of each destination vertex. Add any vertices that have an in-degree of 0 to the queue.<\/li>\n<li>Repeat until the queue is empty. If the size of the result list is not equal to the number of input vertices, it means a cycle exists, so return <code>-1<\/code>.<\/li>\n<\/ol>\n<h2>Basic Code Implementation<\/h2>\n<p>Below is a basic implementation of topological sorting in C++.<\/p>\n<pre><code>\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;queue&gt;\nusing namespace std;\n\nvoid topologicalSort(int n, vector&lt;vector&lt;int&gt;&gt; &amp;graph) {\n    vector&lt;int&gt; inDegree(n + 1, 0);\n    vector&lt;int&gt; result;\n\n    \/\/ Calculate in-degree\n    for (int i = 1; i &lt;= n; i++) {\n        for (int j : graph[i]) {\n            inDegree[j]++;\n        }\n    }\n\n    queue&lt;int&gt; q;\n\n    \/\/ Insert vertices with in-degree 0 into the queue\n    for (int i = 1; i &lt;= n; i++) {\n        if (inDegree[i] == 0) {\n            q.push(i);\n        }\n    }\n\n    while (!q.empty()) {\n        int u = q.front();\n        q.pop();\n        result.push_back(u);\n\n        for (int v : graph[u]) {\n            inDegree[v]--;\n            if (inDegree[v] == 0) {\n                q.push(v);\n            }\n        }\n    }\n\n    \/\/ Check for cycles\n    if (result.size() != n) {\n        cout &lt;&lt; -1 &lt;&lt; endl;\n    } else {\n        for (int i = 0; i &lt; result.size(); i++) {\n            cout &lt;&lt; result[i] &lt;&lt; ' ';\n        }\n        cout &lt;&lt; endl;\n    }\n}\n\nint main() {\n    int n, m;\n    cin &gt;&gt; n &gt;&gt; m;\n    vector&lt;vector&lt;int&gt;&gt; graph(n + 1);\n\n    for (int i = 0; i &lt; m; i++) {\n        int x, y;\n        cin &gt;&gt; x &gt;&gt; y;\n        graph[x].push_back(y);\n    }\n\n    topologicalSort(n, graph);\n    return 0;\n}\n    <\/code><\/pre>\n<h2>Code Explanation<\/h2>\n<p>In the above code, we first declare an array called <code>inDegree<\/code> to hold the in-degrees. After computing the in-degrees of each vertex, we add the vertices with in-degree 0 to the queue. Next, we take a vertex from the queue, remove all edges going out from that vertex, and update the in-degrees. If the size of the <code>result<\/code> list is not equal to the number of vertices, it indicates that a cycle exists, so we print <code>-1<\/code>.<\/p>\n<h2>Complexity Analysis<\/h2>\n<p>The time complexity of topological sorting is <code>O(N + M)<\/code>, where <code>N<\/code> is the number of vertices and <code>M<\/code> is the number of edges. It takes <code>O(M)<\/code> time to count the in-degrees, and updating the in-degrees for each vertex also takes <code>O(M)<\/code>. Therefore, the overall time complexity is <code>O(N + M)<\/code>. The space complexity is <code>O(N + M)<\/code>, considering the list to store the graph and the in-degree array.<\/p>\n<h2>Additional Practice Problems<\/h2>\n<p>Deepen your understanding and application of topological sorting through the following additional practice problems.<\/p>\n<ol>\n<li>Create various combinations of tasks based on the given tasks and apply topological sorting.<\/li>\n<li>Implement appropriate error handling when given a graph that contains cycles.<\/li>\n<li>If there are multiple vertices with the same in-degree, implement it so that one of the vertices is randomly selected.<\/li>\n<\/ol>\n<h2>Conclusion<\/h2>\n<p>In this post, we learned about the concept and implementation of topological sorting, as well as how to apply it through an example problem. Topological sorting is an algorithm that is widely used in various fields, so it is important to understand it well and practice sufficiently.<\/p>\n<p>Now you should feel confident using topological sorting to organize and manage complex tasks. Keep practicing and solving various problems!<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this article, we will learn about topological sorting. Topological sorting is an algorithm for linearly arranging the vertices in a directed acyclic graph (DAG), which is useful when a specific order needs to be maintained. For example, it is used when handling task dependencies or for compilers to determine the execution order of &hellip; <a href=\"https:\/\/atmokpo.com\/w\/34272\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;C++ Coding Test Course, Topological Sorting&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[111],"tags":[],"class_list":["post-34272","post","type-post","status-publish","format-standard","hentry","category-c-coding-test-tutorials-2"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/34272\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this article, we will learn about topological sorting. Topological sorting is an algorithm for linearly arranging the vertices in a directed acyclic graph (DAG), which is useful when a specific order needs to be maintained. For example, it is used when handling task dependencies or for compilers to determine the execution order of &hellip; \ub354 \ubcf4\uae30 &quot;C++ Coding Test Course, Topological Sorting&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/34272\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:26:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T10:57:54+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"C++ Coding Test Course, Topological Sorting\",\"datePublished\":\"2024-11-01T09:26:16+00:00\",\"dateModified\":\"2024-11-01T10:57:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/\"},\"wordCount\":577,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"C++ Coding Test Tutorials\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/\",\"url\":\"https:\/\/atmokpo.com\/w\/34272\/\",\"name\":\"C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:26:16+00:00\",\"dateModified\":\"2024-11-01T10:57:54+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/34272\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/34272\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"C++ Coding Test Course, Topological Sorting\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/34272\/","og_locale":"ko_KR","og_type":"article","og_title":"C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this article, we will learn about topological sorting. Topological sorting is an algorithm for linearly arranging the vertices in a directed acyclic graph (DAG), which is useful when a specific order needs to be maintained. For example, it is used when handling task dependencies or for compilers to determine the execution order of &hellip; \ub354 \ubcf4\uae30 \"C++ Coding Test Course, Topological Sorting\"","og_url":"https:\/\/atmokpo.com\/w\/34272\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:26:16+00:00","article_modified_time":"2024-11-01T10:57:54+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/34272\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/34272\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"C++ Coding Test Course, Topological Sorting","datePublished":"2024-11-01T09:26:16+00:00","dateModified":"2024-11-01T10:57:54+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/34272\/"},"wordCount":577,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["C++ Coding Test Tutorials"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/34272\/","url":"https:\/\/atmokpo.com\/w\/34272\/","name":"C++ Coding Test Course, Topological Sorting - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:26:16+00:00","dateModified":"2024-11-01T10:57:54+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/34272\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/34272\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/34272\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"C++ Coding Test Course, Topological Sorting"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34272","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=34272"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34272\/revisions"}],"predecessor-version":[{"id":34273,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/34272\/revisions\/34273"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=34272"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=34272"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=34272"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}