Cod sursa(job #2797959)

Utilizator Angel2IonitaAngel Ionita Angel2Ionita Data 10 noiembrie 2021 19:44:54
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <vector>
#include <fstream>
#include <stack>
using namespace std;

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

class Graph
{
    vector<vector<int>> adjList;
    int size;

public:
    Graph(int n)
    {
        size = n;
        adjList.resize(size);
    }
    void addEdge(int start, int end)
    {
        adjList[start].push_back(end);
    }
    void DFS(int node,vector<bool>& vis,stack<int>& S)
    {
        vis[node] = true;
        for (auto i : adjList[node])
            if (!vis[i])
                DFS(i,vis,S);
        S.push(node);
    }
    void tS()
    {
    stack<int> S;
    vector<bool> vis;
    for (int i = 0; i < size; i++)
        vis.push_back(false);
    for (int i = 0; i < size; i++)
        if (!vis[i])
            DFS(i,vis,S);
    while(!S.empty())
    {
        o<<S.top()+1<<" ";
        S.pop();
    }
    }
};

int main()
{

    int n, m;
    int x, y;
    f >> n >> m;
    Graph g(n);
    for (int i = 1; i <= m; i++)
    {
        f >> x >> y;
        g.addEdge(x-1, y-1);
    }
    g.tS();
    return 0;
}