Cod sursa(job #2797717)

Utilizator StefaniaCriStefania Cristea StefaniaCri Data 10 noiembrie 2021 14:45:23
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

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

vector<int> la[100007];
int n,m,x,y;

void dfs_plus(int i, stack<int> &my_stack, int visited[])
{
    visited[i]=1;
    for(int j:la[i])
    {
        if(!visited[j])
            dfs_plus(j,my_stack,visited);
    }
    my_stack.push(i);
}

void topologic()
{
    stack <int> Stack;
    int visited[n+1];

    for(int i=1; i<n+1; i++)
        if(!visited[i])
           dfs_plus(i,Stack,visited);

    while(!Stack.empty())
        {
          g<<Stack.top()<<" ";
          Stack.pop();
        }
}

int main()
{
     f>>n>>m;
     for(int i=0;i<m;i++)
     {
      f>>x>>y;
      la[x].push_back(y);
     }
     f.close();
     topologic();
     g.close();
     return 0;
}