Advertisement
viligen

topological_sorting_1_source_removal

Aug 9th, 2022 (edited)
421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. def get_pred_count(graph):
  2.     result = {}
  3.     for node, children in graph.items():
  4.         if node not in result:
  5.             result[node] = 0
  6.         for child in children:
  7.             if child not in result:
  8.                 result[child] = 0
  9.             result[child] += 1
  10.     return result
  11.  
  12.  
  13. def find_node_with_zero_count(pred_counts):
  14.     for node, count in pred_counts.items():
  15.         if count == 0:
  16.             return node
  17.     return None
  18.  
  19.  
  20. def top_sort(graph, pred_counts):
  21.     removed_nodes = []
  22.     while pred_counts:
  23.         node = find_node_with_zero_count(pred_counts)
  24.         if node is None:
  25.             break
  26.  
  27.         removed_nodes.append(node)
  28.         del pred_counts[node]
  29.         for child in graph[node]:
  30.             pred_counts[child] -= 1
  31.  
  32.     return removed_nodes
  33.  
  34.  
  35. n = int(input())
  36. graph = {}
  37.  
  38. for _ in range(n):
  39.     line = input().split('->')
  40.     if len(line) == 1 or line[1] == '':
  41.         graph[line[0].strip()] = []
  42.     else:
  43.         graph[line[0].strip()] = line[1].strip().split(', ')
  44.  
  45. pred_counts = get_pred_count(graph)
  46.  
  47. result = top_sort(graph, pred_counts)
  48.  
  49. if pred_counts:
  50.     print('Invalid topological sorting')
  51. else:
  52.     print(f'Topological sorting: {", ".join(result)}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement