Cod sursa(job #3294321)

Utilizator jumaracosminJumara Cosmin-Mihai jumaracosmin Data 21 aprilie 2025 13:58:18
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

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

//#define fin std::cin 
//#define fout std::cout 

const int NMAX = 5e4 + 5;

int n, m;
std::vector<int> G[NMAX];

int in_deg[NMAX];

std::vector<int> top_sort()
{
    for(int i = 1; i <= n; ++i)
        for(auto node : G[i])
            in_deg[node]++;

    std::queue<int> q;
    for(int i = 1; i <= n; ++i)
        if(in_deg[i] == 0)
            q.push(i);

    std::vector<int> sorted;

    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        sorted.push_back(node);

        for(auto adj : G[node])
        {
            in_deg[adj]--;
            if(in_deg[adj] == 0)
                q.push(adj);
        }
        
    }

    return sorted;
}

int main() 
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }

    std::vector<int> ans = top_sort();

    for(auto node : ans)
        fout << node << " ";

    return 0;
}