Cod sursa(job #3340980)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 17 februarie 2026 16:08:40
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
const int NMAX = 50001;
int n, m, in[NMAX];
vector<int> adj[NMAX], sorted;

void topsort()
{
    queue<int> Q;
    for(int node = 1; node <= n; node++)
        if(in[node] == 0)
            Q.push(node);
    while(!Q.empty())
    {
        int node = Q.front(); Q.pop();
        sorted.push_back(node);
        for(int next : adj[node])
        {
            in[next]--;
            if(in[next] == 0)
                Q.push(next);
        }
    }
}

int main()
{
    fin >> n >> m;
    while(m--)
    {
        int u, v;
        fin >> u >> v;
        adj[u].push_back(v);
        in[v]++;
    }
    topsort();
    for(int node : sorted)
        fout << node << " ";

    fin.close();
    fout.close();
    return 0;
}