Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Course Schedule

#include <bits/stdc++.h>
using namespace std;

class Graph {
  public:
    int n;
    vector<vector<int>> adj;
    vector<int> indegree;

    Graph(int n) {
        this->n = n;
        adj.resize(n);
        indegree.resize(n);
    }

    void topological_sort() {
        // Populate indegrees.
        for (int u = 0; u < n; u++) {
            for (auto child : adj[u]) {
                indegree[child]++;
            }
        }

        queue<int> q;
        for (int i = 0; i < n; i++) {
            if (indegree[i] == 0) {
                q.push(i);
            }
        }

        vector<int> res;
        while (!q.empty()) {
            int now = q.front();
            q.pop();
            res.push_back(now);

            for (auto child : adj[now]) {
                indegree[child]--;
                if (indegree[child] == 0) {
                    q.push(child);
                }
            }
        }

        // If there is a cycle, the cycle vertices would never have indegree
        // zero. Hence, they'd never be processed.
        if ((int)res.size() != n) {
            cout << "IMPOSSIBLE"
                 << "\n";
            return;
        }

        for (int i = 0; i < n; i++) {
            cout << res[i] + 1 << " ";
        }
        cout << "\n";
    }
};

void solve() {
    int n, m;
    cin >> n >> m;

    Graph g(n);
    for (int i = 0; i < m; i++) {
        int x, y;
        cin >> x >> y;
        x--;
        y--;
        g.adj[x].push_back(y);
    }

    g.topological_sort();
}

int main() {
    solve();
    return 0;
}