【題解】CSES 1679 Course Schedule

【題目敘述】https://cses.fi/problemset/task/1679/

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
 
int n, m, a, b, in[100005];
vector <int> v[100005], ans;
 
int main() {
    cin >> n >> m;
    for (int i = 0; i < m; i++){
        cin >> a >> b;
        v[a].push_back(b);
        in[b]++;
    }
    queue <int> q;
    for (int i = 1; i <= n; i++){
        if (in[i] == 0) q.push(i);
    }
    while (!q.empty()){
        int now = q.front();
        q.pop();
        ans.push_back(now);
        for (int i:v[now]){
            in[i]--;
            if (in[i] == 0) q.push(i);
        }
    }
    if (ans.size() != n) cout << "IMPOSSIBLE\n";
    else{
        for (int i:ans){
            cout << i << " ";
        }
    }
}
分享本文 Share with friends