Cod sursa(job #3352569)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 28 aprilie 2026 20:48:52
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e5;
vector<int> G[NMAX + 1];
int gi[NMAX + 1]; //gi[i] = gradul interior al lui i
queue<int> q;
vector<int> topsort;

int main() {
    ifstream cin("sortaret.in");
    ofstream cout("sortaret.out");
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        G[x].push_back(y);
        gi[y]++;
    }
    for(int i = 1; i <= n; i++) {
        if(gi[i] == 0) {
            q.push(i);
        }
    }
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        topsort.push_back(x);
        for(auto it : G[x]) {
            gi[it]--;
            if(gi[it] == 0) {
                q.push(it);
            }
        }
    }
    for(auto it : topsort) {
        cout << it << ' ';
    }

}