Topological Sort
Xem dạng PDF
Gửi bài giải
Điểm:
100,00
Giới hạn thời gian:
2.0s
Giới hạn bộ nhớ:
256M
Tác giả:
Dạng bài
Ngôn ngữ cho phép
Python
Problem Statement
Given a directed graph with n nodes and m edges, output a topological ordering of the nodes. If the graph contains a cycle, output "CYCLE".
Use Kahn's algorithm with a min-heap for tie-breaking (always process the node with the smallest index first).
Algorithm:
- Compute in-degrees for all nodes.
- Initialize a min-heap with all nodes of in-degree 0.
- Repeatedly extract the smallest node, add to the result, and decrement in-degrees of its neighbors. Push any neighbor whose in-degree drops to 0 into the heap.
- If the result has fewer than
nnodes, a cycle exists.
Function signature:
def topo_sort(n: int, edges: list) -> list | None:
# edges: list of (u, v) — directed edge from u to v
# returns sorted order as list, or None if cycle detected
Input Format
Line 1: n m — number of nodes and directed edges
Lines 2..m+1: u v — directed edge from u to v
Output Format
If no cycle: space-separated node indices in topological order
If cycle: CYCLE
Example
Input:
6 6
5 2
5 0
4 0
4 1
2 3
3 1
Output:
4 5 0 2 3 1
Notes
- The min-heap tie-breaking ensures a deterministic, lexicographically smallest valid topological order.
- Node 4 and 5 both have in-degree 0; 4 is processed first (smaller index).
- Topological sort is only possible for Directed Acyclic Graphs (DAGs).
Bình luận