Untitled

 avatar
unknown
plain_text
a year ago
1.2 kB
5
Indexable
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define endl "\n"
 
const double PI = 3.14159265358979;
const ll INF =  1e18 + 7;
const ll MOD = 1e9 + 7;
const ll nax = 100005;
const int LOG = 25;


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

    vector<int> adj[n + 1];
    vector<int> indeg(n + 1, 0);

    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        adj[x].push_back(y);
        indeg[y]++;
    }

    priority_queue<int> pq;
    for (int i = 1; i <= n; i++) {
        if (indeg[i] == 0) {
            pq.push(-i);
        }
    }

    vector<int> order;
    while(!pq.empty()) {
        int cur = -pq.top();
        pq.pop();
        order.push_back(cur);

        for (int v: adj[cur]) {
            indeg[v]--;
            if (indeg[v] == 0) {
                pq.push(-v);
            }
        }
    }

    if (order.size() != n) {
        cout << "-1";
    } else {
        for (int x: order) {
            cout << x << " ";
        }
    }
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    // int t; cin >> t; while(t--)
    solve();
    return 0;
}
Editor is loading...
Leave a Comment