Eman_sh's blog

By Eman_sh, history, 2 months ago, In English

Hello Codeforces!

What is Topological Sort?

Topological Sort is an algorithm used to arrange nodes in a linear sequence. If there is a condition that node $$$u$$$ must be completed before node $$$v$$$, then $$$u$$$ must appear first in the ordering.

To visualize it simply, think of it as a "prerequisite tree." For example, you cannot study a Data Structures (DS) course before you finish Introduction to Programming.

Time Complexity: $$$O(V + E)$$$


Implementation in Python

In Python, there is a handy built-in library called graphlib that does this sorting easily. All you have to do is pass it a Dictionary containing each subject and a List of the subjects that must be finished before it:

from graphlib import TopologicalSorter, CycleError

# Dictionary containing each subject and its prerequisites
preds = {
    1: [],     # Subject 1 has no prerequisites
    2: [1],    # Subject 2 requires subject 1 to be finished first
    3: [1, 2]  # Subject 3 requires subjects 1 and 2
}

ts = TopologicalSorter(preds)

try:
    order = list(ts.static_order())
    print("Study Order:", *order) # Study Order: 1 2 3
except CycleError:
    print("-1\n")

Happy coding!

  • Vote: I like it
  • +2
  • Vote: I do not like it

»
2 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Bro just post a Python libary and don't explain any steps of the topological Sort.

»
2 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Eman_sh (previous revision, new revision, compare).

»
2 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Can you use it in Codeforces or other programming competitions?

  • »
    »
    2 months ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Yes you can It's a built-in library in Python 3.9+

    • »
      »
      »
      2 months ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      I think it may break fair in some easy rounds. It will help those participants who use Python.

      • »
        »
        »
        »
        2 months ago, hide # ^ |
        ← Rev. 2  
        Vote: I like it 0 Vote: I do not like it

        There is not a SINGLE rule that prohibits using features on a programming language. Even if there was, it'd be dumb as fuck.

        Would it make sense to make codeforces not support python because it grants a disadvantage to those that use C++?

        Would it make sense to make every single language banned and replaced with Brainfuck so that it's "perfectly fair"?

      • »
        »
        »
        »
        2 months ago, hide # ^ |
         
        Vote: I like it 0 Vote: I do not like it

        C++ has STL and pbds with lots of algotithms and data structures. And I don't think that topological sort is too hard to write.