Topological sort with the smallest available vertex
I am trying to solve a problem based on TopSort. Since there will be a number of valid topological sorted orders, I need to output the one that is lexicographically smallest, i.e. The smallest numbered vertex available first.
I will explain the method I adopted and then post the code. I saved an array that contains the number of inline edges for each node of the graph. There is also an adjacency matrix. I have a boolean array "visited" that stores the number of nodes visited and the minimum priority queue to pull the smallest available vertex at that moment. Here is my code:
void dfs(int u){
visited[u] = true;
cout<<u<<" ";
list<int>::iterator i;
for(i = adj[u].begin(); i != adj[u].end(); ++i){
if(!visited[*i]){
inedge[*i]--;
if(!inedge[*i]){
pq.push(*i);
}
if(!pq.empty()){
int temp = pq.top();
pq.pop();
dfs(temp);
}
}
}
}
Now, when this function is called for the first time, the priority queue contains only those nodes for which inedge [i] = 0 (the number of edges is zero). I pull the minimum node out of this priority queue u = pq.top()
and call dfs(u)
.
But my code is giving wrong outputs. Can anyone help me if the logic I used here is not correct?
My input consists of N incomplete sequences (with missing numbers in each of the N). Input data:
2
1 3
2 3 4
Output:
1 2 3 4
This is the correct expected output and my code is actually generating this. But for the input given in this image Input data:
6
7 8 9
7 11 9
5 11 2
3 8 9
11 10
3 10
Expected Result:
3 5 7 8 11 2 9 10
My code output:
3 5 7 8 11 9 2 10
My code is displaying incorrect results for several other test cases, but I don't know how to fix this problem.
source to share
The problem is what pq.top
is called before all outgoing edges of the current node have been checked.
Consider the following graph: Nodes: A, B, C; Edges A-> B, AC. Let C have a lower priority value, i.e. It should come first. During dfs (A), you check B before C. Since it is immediately taken off the queue again, B is processed first (but should not). So add all neighbors before re-requesting the queue.
source to share