CSES Solutions
#1679Graph Algorithms

Course Schedule

View on CSES

Solution

1679-Course_Schedule.cpp
1#include<bits/stdc++.h>
2using namespace std;
3#define int long long
4vector<int> topo_sort(int n, vector<vector<int>> &adj) {
5    vector<int> in(n, 0), res;
6    for (auto &v : adj) for (int u : v) in[u]++;
7    queue<int> q;
8    for (int i = 0; i < n; i++) if (!in[i]) q.push(i);
9    while (!q.empty()) {
10        int v = q.front(); q.pop(); res.push_back(v);
11        for (int u : adj[v]) if (--in[u] == 0) q.push(u);
12    }
13    return res.size() == n ? res : vector<int>();
14}
15signed main(){
16  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
17  int n,m; cin>>n>>m;
18  vector<vector<int>> adj(n);
19  for(int i=0;i<m;++i){
20    int a,b; cin>>a>>b;
21    --a,--b;
22    adj[a].emplace_back(b);
23  }
24  vector<int> topo_order=topo_sort(n,adj);
25  if(topo_order.size()){
26    for(auto&x:topo_order) cout<<x+1<<" ";
27    cout<<'\n';
28  }else{
29    cout<<"IMPOSSIBLE\n";
30  }
31  return 0;
32}

Editorial not yet generated for this problem. Run the editorial generation script to add hints and detailed explanations.