Cod sursa(job #3307203)

Utilizator Andrei-Dani-10Pisla Andrei Daniel Andrei-Dani-10 Data 18 august 2025 20:41:48
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 50000;
int n, m, a, b, toposort[nmax + 2];
vector <int> muchii[nmax + 2];

int visited[nmax + 2];
void dfs(int node){
    visited[node] = 1;
    for(auto nxt : muchii[node])
        if(!visited[nxt]) dfs(nxt);
    toposort[toposort[0]--] = node;
}

int indegree[nmax + 2];

int main(){

    in>>n>>m;
    for(int i = 1; i <= m; i++){
        in>>a>>b;
        muchii[a].push_back(b);
        indegree[b]++;
    }

    toposort[0] = n; ///reverse
    for(int i = 1; i <= n; i++)
        if(!indegree[i]) dfs(i);

    for(int it = 1; it <= n; it++)
        out<<toposort[it]<<" "; out<<"\n";

    return 0;
}