Cod sursa(job #3348919)

Utilizator popescumalinaPopescu Malina popescumalina Data 24 martie 2026 17:39:38
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int NMAX = 100000;

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

int N, M;
vector<int> G[NMAX + 1],
       L;
bool viz[NMAX + 1];

void citire()
{
    int x, y;
    f >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
    }
}

void DFS(int x)
{
    viz[x] = 1;
    for(const int &y : G[x])
        if(viz[y] == 0)
            DFS(y);
    L.push_back(x);
}

int main()
{
    citire();
    for(int i = 1; i <= N; i++)
        if(viz[i] == 0)
            DFS(i);
    for(int i = L.size() - 1; i >= 0; i--)
        g << L[i] << ' ';
    f.close();
    g.close();
    return 0;
}