#include #include enum color { WHITE, GRAY, BLACK }; typedef int Node; typedef std::vector> List; typedef std::vector Colors; void dfs_visit(List& neighbours, Colors& colors, std::vector& top_sort, int u) { colors[u] = GRAY; for (int v : neighbours[u]) { if (colors[v] == WHITE) { dfs_visit(neighbours, colors, top_sort, v); } else if (colors[v] == GRAY){ std::cout << "Cycle!" << std::endl; exit(EXIT_SUCCESS); } } colors[u] = BLACK; top_sort.push_back(u); } void topological_sort(List& neighbours) { const int n = neighbours.size(); std::vector colors(n, WHITE); std::vector top_sort; for (int u = 1; u < n; u++) { if (colors[u] == WHITE) { dfs_visit(neighbours, colors, top_sort, u); } } for (int i = top_sort.size() - 1; i >= 0 ; i--) { std::cout << top_sort[i] + 1 << std::endl; } } int main(int argc, const char *argv[]) { int n; std::cin >> n; List neighbours(n); for (Node u = 0; u < n; u++) { int k; std::cin >> k; for (int i = 0; i < k; i++) { Node v; std::cin >> v; neighbours[u].push_back(v); } } topological_sort(neighbours); return 0; }