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!









Bro just post a Python libary and don't explain any steps of the topological Sort.
i literally thought its another long AI post about this topic :skull:
It's just a quick Python trick
Auto comment: topic has been updated by Eman_sh (previous revision, new revision, compare).
Can you use it in Codeforces or other programming competitions?
Yes you can It's a built-in library in Python 3.9+
I think it may break fair in some easy rounds. It will help those participants who use Python.
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"?
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.