2024-07-24 15:57:30 +02:00
|
|
|
// Algorithm outputting a topological order of a directed graph
|
|
|
|
// Authors: Georǵi Kocharyan
|
2024-07-24 15:54:43 +02:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
#include <cstdio>
|
|
|
|
#include <vector>
|
|
|
|
#include <stack>
|
|
|
|
|
|
|
|
#include "../digraph.h"
|
|
|
|
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
int size = 10;
|
|
|
|
Digraph G(size);
|
|
|
|
G.add_edge(3,4);
|
|
|
|
G.add_edge(6,7);
|
|
|
|
G.add_edge(7,5);
|
|
|
|
|
2024-07-24 15:57:30 +02:00
|
|
|
// keeps track of vertices with zero indegree, these can be put at the beginning
|
2024-07-24 15:54:43 +02:00
|
|
|
std::stack<int> zero_indegree;
|
2024-07-24 15:57:30 +02:00
|
|
|
|
2024-07-24 15:54:43 +02:00
|
|
|
std::vector<int> indegs = G.indegrees();
|
|
|
|
int amount = 0;
|
|
|
|
|
|
|
|
for(int i = 0; i < size; i++)
|
|
|
|
{
|
|
|
|
if (indegs[i] == 0)
|
|
|
|
{
|
|
|
|
zero_indegree.push(i);
|
|
|
|
amount++;
|
|
|
|
}
|
|
|
|
}
|
2024-07-24 15:57:30 +02:00
|
|
|
// update indegs, zero_indegree after adding a vertex to the top. order
|
2024-07-24 15:54:43 +02:00
|
|
|
while(!zero_indegree.empty())
|
|
|
|
{
|
|
|
|
int node_id = zero_indegree.top();
|
|
|
|
zero_indegree.pop();
|
|
|
|
std::cout << node_id << ' ';
|
|
|
|
for(auto i: G.adjList(node_id))
|
|
|
|
{
|
2024-07-24 15:57:30 +02:00
|
|
|
if (indegs[i] = 1) // this ensures each vertex added to stack only once
|
2024-07-24 15:54:43 +02:00
|
|
|
{
|
|
|
|
zero_indegree.push(i);
|
|
|
|
amount++;
|
|
|
|
}
|
|
|
|
indegs[i]--;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!(amount == size))
|
|
|
|
{
|
|
|
|
std::cout << '\n' << "The graph contains cycles and thus has no topological order." << std::endl;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|