12tqian's Competitive Programming Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub 12tqian/cp-library

:heavy_check_mark: Topological Sort
(library/graphs/topological-sort.hpp)

Topological Sort

Functions

Resources

Verified with

Code

#pragma once

std::vector<int> topo_sort(std::vector<std::vector<int>> adj) {
	int n = (int)adj.size();
	std::vector<int> in(n);
	std::vector<int> res;
	std::list<int> todo;
	for (int i = 0; i < n; i++) {
		for (int j : adj[i]) {
			++in[j];
		}
	}
	for (int i = 0; i < n; i++) {
		if (!in[i]) {
			todo.push_back(i);
		}
	}
	while (!todo.empty()) {
		int x = todo.front();
		todo.pop_front();
		res.push_back(x);
		for (int nxt : adj[x]) {
			if (!(--in[nxt])) {
				todo.push_back(nxt);
			}
		}
	}
	return res;
}
std::vector<int> topo_sort(std::vector<std::vector<int>> adj) {
	int n = (int)adj.size();
	std::vector<int> in(n);
	std::vector<int> res;
	std::list<int> todo;
	for (int i = 0; i < n; i++) {
		for (int j : adj[i]) {
			++in[j];
		}
	}
	for (int i = 0; i < n; i++) {
		if (!in[i]) {
			todo.push_back(i);
		}
	}
	while (!todo.empty()) {
		int x = todo.front();
		todo.pop_front();
		res.push_back(x);
		for (int nxt : adj[x]) {
			if (!(--in[nxt])) {
				todo.push_back(nxt);
			}
		}
	}
	return res;
}
Back to top page