Guest User

Untitled

a guest
Mar 28th, 2019
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. from itertools import combinations
  2. from collections import defaultdict
  3.  
  4.  
  5. def dfs(st, end, valid):
  6.     todo = [st]
  7.     vis = set([st])
  8.     while len(todo) > 0:
  9.         cur = todo.pop()
  10.         if cur == end:
  11.             return True
  12.         vis.add(cur)
  13.         for ne in graph[cur]:
  14.             if ne in valid and ne not in vis:
  15.                 todo.append(ne)
  16.                 vis.add(ne)
  17.     return False
  18.  
  19.  
  20. case = 0
  21. while True:
  22.     case += 1
  23.     n, m = map(int, input().split())
  24.     if n == m == 0:
  25.         break
  26.  
  27.     graph = defaultdict(list)
  28.  
  29.     for _ in range(m):
  30.         x, y = map(int, input().split())
  31.         graph[x - 1].append(y - 1)
  32.     all_ = set(range(n))
  33.     if not dfs(0, 1, all_) or not dfs(1, 0, all_):
  34.         print("Network {}\nIMPOSSIBLE\n".format(case))
  35.         continue
  36.  
  37.     number = 0
  38.     res = -1
  39.     while True:
  40.         for psol in combinations(range(n), number):
  41.             val = set(psol) | {0, 1}
  42.             if dfs(0, 1, val) and dfs(1, 0, val):
  43.                 res = number + 2
  44.                 break
  45.         if res != -1:
  46.             break
  47.         number += 1
  48.     print("Network {}\nMinimum number of nodes = {}\n".format(case, res))
Advertisement
Add Comment
Please, Sign In to add comment