Cod sursa(job #2918663)

Utilizator bumblebeeGeorge Bondar bumblebee Data 12 august 2022 13:18:03
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#include <vector>
#include <stack>
#define MAXN 50000
using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

vector<int> g[MAXN + 1];
stack<int> vertices;
int visited[MAXN + 1];

void sortTopological(int currentVertex) {
    visited[currentVertex] = 1;
    for (int &neighbour : g[currentVertex]) {
        if (!visited[neighbour]) {
            sortTopological(neighbour);
        }   
    }
    vertices.push(currentVertex);
}

int main() {
    int n, m, nodeA, nodeB;
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        fin >> nodeA >> nodeB;
        g[nodeA].push_back(nodeB);
    }
    for (int i = 1; i <= n; ++i) {
        if (!visited[i]) {
            sortTopological(i);
        }
    }
    while (!vertices.empty()) {
        fout << vertices.top() << " ";
        vertices.pop();
    }
    return 0;
}