Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def get_pred_count(graph):
- result = {}
- for node, children in graph.items():
- if node not in result:
- result[node] = 0
- for child in children:
- if child not in result:
- result[child] = 0
- result[child] += 1
- return result
- def find_node_with_zero_count(pred_counts):
- for node, count in pred_counts.items():
- if count == 0:
- return node
- return None
- def top_sort(graph, pred_counts):
- removed_nodes = []
- while pred_counts:
- node = find_node_with_zero_count(pred_counts)
- if node is None:
- break
- removed_nodes.append(node)
- del pred_counts[node]
- for child in graph[node]:
- pred_counts[child] -= 1
- return removed_nodes
- n = int(input())
- graph = {}
- for _ in range(n):
- line = input().split('->')
- if len(line) == 1 or line[1] == '':
- graph[line[0].strip()] = []
- else:
- graph[line[0].strip()] = line[1].strip().split(', ')
- pred_counts = get_pred_count(graph)
- result = top_sort(graph, pred_counts)
- if pred_counts:
- print('Invalid topological sorting')
- else:
- print(f'Topological sorting: {", ".join(result)}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement