Cod sursa(job #2670464)

Utilizator robeert.77Chirica Robert robeert.77 Data 9 noiembrie 2020 21:57:14
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("sortaret.in");
ofstream fout ("sortaret.out");

int main() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    int n, m;
    fin >> n >> m;
    int inDegree[n + 1] = {0}, a, b;
    vector<int> graph[n + 1];
    for (int i = 0; i < m; i++) {
        fin >> a >> b;
        graph[a].push_back(b);
        inDegree[b]++;
    }
    
    queue<int> nodes;
    for (int i = 1; i <= n; i++)
        if (!inDegree[i])
            nodes.push(i);

    while (!nodes.empty()) {
        fout << nodes.front() << " ";
        for (vector<int>::iterator it = graph[nodes.front()].begin(); it != graph[nodes.front()].end(); it++) {
            inDegree[*it]--;
            if (!inDegree[*it])
                nodes.push(*it);
        }
        nodes.pop();
    }
    return 0;
}