Cod sursa(job #3318773)

Utilizator PaulTPaul Tirlisan PaulT Data 28 octombrie 2025 19:13:58
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

int n, m;
vector<vector<int>> G;
vector<bool> seen;
stack<int> stk;

void Read();
void Dfs(int x);
void Write();

int main()
{
    Read();
    for (int x = 1; x <= n; ++x)
        if (!seen[x])
            Dfs(x);
    Write();
}

void Read()
{
    ifstream fin("sortaret.in");
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    seen = vector<bool>(n + 1);
    
    int x, y;
    for (int i = 0; i < m; ++i)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
    
    fin.close();
}

void Dfs(int x)
{
    seen[x] = true;
    for (const int y: G[x])
        if (!seen[y])
            Dfs(y);
    
    stk.push(x);
}

void Write()
{
    ofstream fout("sortaret.out");
    while (!stk.empty())
    {
        fout << stk.top() << ' ';
        stk.pop();
    }
}