Cod sursa(job #3349112)

Utilizator stefangr2008Grecu Stefan stefangr2008 Data 25 martie 2026 15:29:07
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
const int NMAX = 50005;

int N, M, gr[NMAX];
vector<int> G[NMAX], L;
queue<int> Q;

ifstream f("sortaret.in");
ofstream g("sortaret.out");

void citire()
{
    int x, y;
    f >> N >> M;
    while(M--)
    {
        f >> x >> y;
        G[x].push_back(y);
        gr[y]++;
    }
}

void sortaret()
{
    for(int i = 1; i <= N; i++)
        if(gr[i] == 0)
            Q.push(i);
    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();
        L.push_back(x);
        for(const auto &y : G[x])
        {
            gr[y]--;
            if(gr[y] == 0)
                Q.push(y);
        }
    }
}

int main()
{
    citire();
    sortaret();
    for(const auto &x : L)
        g << x << ' ';
    g << '\n';
    f.close();
    g.close();
    return 0;
}