Я создал программу, которая упорядочивает граф по топологической сортировке по заданной диаграмме. Я определил 3 результата:
- ok
- существующие циклы
- недостающая информация
Вывод первых двух пунктов правильный, а третьего нет. Например, для графа с 4 вершинами и ребрами: 1->2; 3->1; 3->4; 4->2, результат, который я получил: 3 1 4 2... неправильно! То, что известно, недостаточно, чтобы сделать такой вывод. Любые подсказки или помощь приветствуются, заранее спасибо.
#include<bits/stdc++.h>
using namespace std;
class Graph{
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int u, int v);
void topologicalSort();
};
Graph::Graph(int V){
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int u, int v){
adj[u].push_back(v);
}
void Graph::topologicalSort(){
vector<int> in_degree(V, 0);
for (int u=0; u<V; u++){
list<int>::iterator itr;
for (itr = adj[u].begin(); itr != adj[u].end(); itr++)
in_degree[*itr]++;}
queue<int> q;
for (int i = 0; i < V; i++)
if (in_degree[i] == 0)
q.push(i);
int cnt = 0;
vector <int> top_order;
while (!q.empty()){
int u = q.front();
q.pop();
top_order.push_back(u);
list<int>::iterator itr;
for (itr = adj[u].begin(); itr != adj[u].end(); itr++)
if (--in_degree[*itr] == 0)
q.push(*itr);
cnt++;}
if (cnt != V){
cout << "Existing cycle\n";
return;}
for (int i=1; i<(int)top_order.size(); i++)
cout << top_order[i] << " ";
cout << endl;
}
int main(){
setbuf(stdout, NULL);
int N, L, u, v;
scanf("%d %d", &N, &L);
Graph g(N+1);
for (int i=1; i<=L; i++){
scanf("%d %d", &u, &v);
g.addEdge(u, v);
}
g.topologicalSort();
return 0;
}