Cod sursa(job #3318356)

Utilizator raul41917raul rotar raul41917 Data 28 octombrie 2025 10:29:13
Problema Sortare topologica Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#include <vector>
#include <queue>
#include <set>

using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

int inDegree[50000];
int main() {

    int n, m;
    fin >> n >> m;

    vector<set<int>> adjacencyList(n + 1, set<int>());
    for(int edgeIndex = 0; edgeIndex < m; edgeIndex++){
        int x, y;
        fin >> x >> y;
        if(adjacencyList[x].count(y) == 0)
            inDegree[y]++;
        adjacencyList[x].insert(y);
    }

    queue<int> nodes;
    for(int i = 1; i <= n; i++)
        if(inDegree[i] == 0)
            nodes.push(i);

    while(!nodes.empty()){
        int frontNode = nodes.front();
        nodes.pop();
        fout << frontNode << " ";

        for(int neighbor: adjacencyList[frontNode]){
            if(--inDegree[neighbor] == 0)
                nodes.push(neighbor);
        }
    }
    return 0;
}