Course Schedule II

Implementation

C++

                                    #include<bits/stdc++.h>
using namespace std;
 
#define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL); cout.tie(NULL);
#define endl '\n'
 
const int N = 200005;
int inDegree[N];
vector<int> adj[N];
void solve() {
    int n,m;
    cin>>n>>m;
 
    vector<int> topsort;
    priority_queue<int> pq;
 
    for(int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        adj[v].push_back(u);
        inDegree[u]++;
    }
    for(int i = 1; i <= n; i++) {
        if(inDegree[i] == 0) {
            pq.push(i); 
        }
    }
 
    while(!pq.empty()) {
        int node = pq.top();
        pq.pop();
        topsort.push_back(node);
        
        for(int neighbor : adj[node]) {
            inDegree[neighbor]--;
            if(inDegree[neighbor] == 0) {
                pq.push(neighbor);
            }
        }
    }
    reverse(topsort.begin(), topsort.end());
    for(auto it : topsort) {
        cout << it << " ";
    }
 
}
 
int main() {
    FASTIO;
 
    solve();
}