The smallest Topological Sort#10651

The smallest Topological Sort (Editorial)

A sequence a = (a_1, a_2, ..., a_n) is lexicographically smaller than a sequence b = (b_1, b_2, ..., b_n) if, at the first position where they differ, a_i < b_i. Therefore, to obtain the lexicographically smallest topological sort, we must place the smallest possible vertex in the first position, then the smallest possible vertex in the second position given the first choice, and so on.

To solve the problem, use Kahn's algorithm. For each vertex, compute its in-degree — the number of edges entering it. A vertex can occupy the next position in the topological sort if and only if all its predecessors have already been placed, that is, its current in-degree is zero.

In the classic version of Kahn's algorithm, vertices with zero in-degree are stored in an ordinary queue and extracted in no particular order. To obtain the lexicographically smallest answer, replace the queue with a priority queue (or a set), from which the vertex with the smallest number is extracted each time.

The algorithm works as follows:

Cycle detection. If the graph contains a cycle, none of the vertices on that cycle will ever reach zero in-degree, so none of them will ever enter the queue. Therefore, if fewer than n vertices end up in the answer when the algorithm terminates, a topological sort is impossible — we print .

Complexity. Each vertex is inserted into and extracted from the priority queue exactly once, and each edge is examined once. The running time is O(n~log~n + m).

Example

The graph provided in the example has the following structure:

The given graph allows multiple options for topological sorting. For example:

The lexicographically smallest topological sort is

1, 3, 4, 2, 6, 5

The lexicographically largest topological sort is

4, 6, 3, 1, 2, 5

Algorithm implementation — set

The input graph is stored as an adjacency list . The in-degrees of the vertices are stored in the array InDegree. The topologically sorted vertices of the graph are stored in the array .

vector<vector<int> > g;
vector<int> InDegree, Order;
set<int> minHeap;

Read the input graph.

scanf("%d %d", &n, &m);
g.resize(n + 1);
InDegree.resize(n + 1);

Calculate the in-degrees for all vertices. For each edge increase the in-degree of vertex .

for (i = 0; i < m; i++)
{
  scanf("%d %d", &a, &b);
  g[a].push_back(b);
  InDegree[b]++;
}

All vertices with a zero in-degree are added to the set .

for (i = 1; i < InDegree.size(); i++)
  if (InDegree[i] == 0) minHeap.insert(i);

The topological sorting algorithm continues as long as the set is not empty.

while (!minHeap.empty())
{

Extract the vertex with the smallest number from and add it to the end of the topological order.

  v = *minHeap.begin();
  minHeap.erase(minHeap.begin());
  Order.push_back(v);

Remove all edges (v, to) outgoing from vertex in the graph. For each such edge, decrease the in-degree of vertex . If the in-degree of vertex becomes zero, add it to the set, from where it will be added to the topological order list.

 for (int to : g[v])
 {
   InDegree[to]--;
   if (InDegree[to] == 0) minHeap.insert(to);
 }
}

If, after executing the algorithm, not all vertices are added to the array , then the graph contains a cycle, and topological sort is impossible.

if (Order.size() < n)
  printf("-1");
else

Print the vertices of the graph in the lexicographically smallest topological order.

  for (i = 0; i < Order.size(); i++)
    printf("%d ", Order[i]);
printf("\n");

Algorithm implementation – priority queue

#include <cstdio>
#include <queue>
#include <vector>
using namespace std;

vector<vector<int> > g;
vector<int> InDegree, Order;
priority_queue<long long, vector<long long>, greater<long long> > pq;
int i, n, m, a, b, v, to;

int main(void)
{
  scanf("%d %d", &n, &m);
  g.resize(n + 1);
  InDegree.resize(n + 1);

  for (i = 0; i < m; i++)
  {
    scanf("%d %d", &a, &b);
    g[a].push_back(b);
    InDegree[b]++;
  }

  for (i = 1; i < InDegree.size(); i++)
    if (InDegree[i] == 0) pq.push(i);

  while (!pq.empty())
  {
    v = pq.top(); pq.pop();
    Order.push_back(v);

    for (int to : g[v])
    {
      InDegree[to]--;
      if (InDegree[to] == 0) pq.push(to);
    }
  }

  if (Order.size() < n)
    printf("-1");
  else
    for (int x : Order)
      printf("%d ", x);
  printf("\n");
  return 0;
}

Java implementation — priority queue

import java.util.*;
import java.io.*;

public class Main
{
  static ArrayList<ArrayList<Integer>> g;
  static ArrayList<Integer> top;
  static int InDegree[];
  static int n, m, flag = 0;
  
  public static void main(String[] args)
  {
    FastScanner con = new FastScanner(System.in);
    n = con.nextInt();
    m = con.nextInt();
    g = new ArrayList<ArrayList<Integer>>();
    InDegree = new int[n+1];
      
    for (int i = 0; i <= n; i++)
      g.add(new ArrayList<Integer>());

    for (int i = 0; i < m; i++)
    {
      int a = con.nextInt();
      int b = con.nextInt();     
      g.get(a).add(b);
      InDegree[b]++;
    }

    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    for(int i = 1; i <= n; i++)
      if (InDegree[i] == 0) pq.add(i);

    top = new ArrayList<Integer>();
    while (!pq.isEmpty())
    {
      int v = pq.poll();
      top.add(v);
      for (int to : g.get(v))
      {
        InDegree[to]--;
        if (InDegree[to] == 0) pq.add(to);
      }
    }

    if (top.size() < n)
      System.out.println("-1");
    else
    {
      for (int x : top) System.out.print(x + " ");
        System.out.println();
    }
  }
}	

class FastScanner
{
  BufferedReader br;
  StringTokenizer st;
 
  public FastScanner(InputStream inputStream)
  {
    br = new BufferedReader(new InputStreamReader(inputStream));
    st = new StringTokenizer("");
  }
 
  public String next()
  {
    while (!st.hasMoreTokens())
    {
      try
      {
        st = new StringTokenizer(br.readLine());
      } catch (Exception e)
      {
        return null;
      }
    }
    return st.nextToken();
  }
 
  public int nextInt()
  {
    return Integer.parseInt(next());
  }
}

Python implementation — priority queue

Import the heappush and functions from the module. is a built-in Python library that provides an implementation of a priority queue based on a heap.

from heapq import heappush, heappop

Read the number of vertices and edges in the graph.

n, m = map(int, input().split())

The input graph is stored as an adjacency list . The in-degrees of the vertices are stored in the array InDegree.

g = [[] for _ in range(n + 1)]
InDegree = [0] * (n + 1)

Read the input graph. Calculate the in-degrees for all vertices. For each edge increase the in-degree of vertex .

for _ in range(m):
  a, b = map(int, input().split())
  g[a].append(b)
  InDegree[b] += 1

All vertices with a zero in-degree are added to the list .

minHeap = []
for i in range(1, len(InDegree)):
  if InDegree[i] == 0:
    heappush(minHeap, i)

The topologically sorted vertices of the graph are stored in the array .

Order = []

The topological sorting algorithm continues as long as the list is not empty.

while minHeap:

Extract the vertex with the smallest number from and add it to the end of the topological order.

  v = heappop(minHeap)
  Order.append(v)

Remove all edges (v, to) outgoing from vertex in the graph. For each such edge, decrease the in-degree of vertex . If the in-degree of vertex becomes zero, add it to the priority queue, from where it will be added to the topological order list.

  for to in g[v]:
    InDegree[to] -= 1
    if InDegree[to] == 0:
      heappush(minHeap, to)

If, after executing the algorithm, not all vertices are added to the array , then the graph contains a cycle, and topological sort is impossible.

if len(Order) < n:
  print(-1)

Print the vertices of the graph in the lexicographically smallest topological order.

else:
  print(*Order)