Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from itertools import combinations
- from collections import defaultdict
- def dfs(st, end, valid):
- todo = [st]
- vis = set([st])
- while len(todo) > 0:
- cur = todo.pop()
- if cur == end:
- return True
- vis.add(cur)
- for ne in graph[cur]:
- if ne in valid and ne not in vis:
- todo.append(ne)
- vis.add(ne)
- return False
- case = 0
- while True:
- case += 1
- n, m = map(int, input().split())
- if n == m == 0:
- break
- graph = defaultdict(list)
- for _ in range(m):
- x, y = map(int, input().split())
- graph[x - 1].append(y - 1)
- all_ = set(range(n))
- if not dfs(0, 1, all_) or not dfs(1, 0, all_):
- print("Network {}\nIMPOSSIBLE\n".format(case))
- continue
- number = 0
- res = -1
- while True:
- for psol in combinations(range(n), number):
- val = set(psol) | {0, 1}
- if dfs(0, 1, val) and dfs(1, 0, val):
- res = number + 2
- break
- if res != -1:
- break
- number += 1
- print("Network {}\nMinimum number of nodes = {}\n".format(case, res))
Advertisement
Add Comment
Please, Sign In to add comment