--- id: toposort title: "Topological Sort" author: Benjamin Qi, Michael Cao prerequisites: - Gold - Breadth First Search - Gold - Introduction to Dynamic Programming description: "?" frequency: 1 --- import { Problem } from "../models"; export const metadata = { problems: { sample: [ new Problem("CSES", "Course Schedule", "1679", "Easy", false, []), ], dp: [ new Problem("CSES", "Longest Flight Route", "1680", "Easy", false, []), ], general: [ new Problem("CSES", "Game Routes", "1681", "Easy", false, [], "counting paths on DAG"), new Problem("Kattis", "Quantum", "https://open.kattis.com/contests/acpc17open/problems/quantumsuperposition", "Easy", false, [], "enumerating paths on DAG"), new Problem("Gold", "Timeline", "1017", "Easy", false, [], "not explicitly given, but graph is a DAG"), new Problem("Gold", "Milking Order", "838", "Normal", false, ["TopoSort", "Binary Search"]), new Problem("CSES", "Course Schedule II", "1681", "Hard", false, [], "equivalent to [Minimal Labels](https://codeforces.com/contest/825/problem/E)"), ], } }; To review, a **directed** graph consists of edges that can only be traversed in one direction. Additionally, a **acyclic** graph defines a graph which does not contain cycles, meaning you are unable to traverse across one or more edges and return to the node you started on. Putting these definitions together, a **directed acyclic** graph, sometimes abbreviated as DAG, is a graph which has edges which can only be traversed in one direction and does not contain cycles. ## Topological Sort A [topological sort](https://en.wikipedia.org/wiki/Topological_sorting) of a directed acyclic graph is a linear ordering of its vertices such that for every directed edge $u\to v$ from vertex $u$ to vertex $v$, $u$ comes before $v$ in the ordering. ## Tutorial both BFS, DFS ### DFS DFS DFS (implementation) ### BFS The BFS version, known as [Kahn's Algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm), makes it obvious how to extract the lexicographically minimum topological sort. (implementation) ## Dynamic Programming Best Path in a DAG One useful property of directed acyclic graphs is, as the name suggests, that no cycles exist. If we consider each node in the graph as a state, we can perform dynamic programming on the graph if we process the states in an order that guarantees for every edge $u\to v$ that $u$ is processed before $v$. Fortunately, this is the exact definition of a topological sort! In this task, we must find the longest path in a DAG. Let $dp[v]$ denote the length of the longest path ending at the node $v$. Clearly $$ dp[v]=\max_{\text{edge } u\to v \text{ exists}}dp[u]+1, $$ or zero if $v$ has in-degree $0$. If we process the states in topological order, it is guarangeed that $dp[u]$ will already have been computed before computing $dp[v]$. (implementation?) ## Problems