Cod sursa(job #2792075)

Utilizator PaulTPaul Tirlisan PaulT Data 31 octombrie 2021 20:24:10
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

ofstream fout("sortaret.out");
int n, m;
vector<vector<int>> G;
stack<int> stk;
vector<int> color;

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

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

void Dfs(int x)
{
    color[x] = 1;
    for (const int& y : G[x])
        switch (color[y])
        {
            case 0: Dfs(y); break;
            case 1: fout << "Cycle!"; return;
            default: break;
        }
    color[x] = 2;
    stk.emplace(x);
}

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

void Read()
{
    ifstream fin("sortaret.in");
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    color = vector<int>(n + 1);
    
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].emplace_back(y);
    }
}