Cod sursa(job #3271526)

Utilizator yawninghorseDragomir Alex yawninghorse Data 26 ianuarie 2025 14:46:46
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;
ifstream cin("sortaret.in");
ofstream cout("sortaret.out");

const int Nmax = 1e5 + 5;
vector<int> lista[Nmax];
int n, m;
bool viz[Nmax];
stack<int> st;

void dfs(int node)
{
    viz[node] = true;
    for(int i = 0; i < lista[node].size(); i++)
    {
        int u = lista[node][i];
        if(viz[u] == false)
            dfs(u);
    }
    st.push(node);
}

void topologicalsort()
{
    for(int i = 1; i <= n; i++)
    {
        if(viz[i] == false)
            dfs(i);
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        lista[x].push_back(y);
    }
    topologicalsort();
    while(!st.empty())
    {
        cout << st.top() << " ";
        st.pop();
    }
}