Advertisement
Guest User

Untitled

a guest
Mar 28th, 2019
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. # https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1571
  2. from itertools import product
  3.  
  4. def floyd_warshall(dist):
  5.     v = len(dist)
  6.     for k in range(v):
  7.         dk = dist[k]
  8.         for i in range(v):
  9.             di = dist[i]
  10.             for j in range(v):
  11.                 if di[j] > di[k] + dk[j]:
  12.                     di[j] = di[k] + dk[j]
  13.  
  14.  
  15. def dijkstra(graph, source):
  16.     q = set()
  17.     dist = {}
  18.     for v in product(range(len(graph)), repeat=2):
  19.         dist[v] = 10e310
  20.         q.add(v)
  21.     dist[source] = 1
  22.  
  23.     while len(q) > 0:
  24.         best = 10e310
  25.         for elem in q:
  26.             if dist[elem] <= best:
  27.                 u = elem
  28.                 best = dist[elem]
  29.         q.remove(u)
  30.         a, b = u
  31.         if a == b == 1:
  32.             break
  33.         for v in q:
  34.             x, y = v
  35.             if x == a or x == b or y == a or y == b: continue
  36.  
  37.             alt = dist[(a, b)] + graph[b][x] + graph[x][y] + graph[y][a] - 1
  38.             if alt < dist[v]:
  39.                 dist[v] = alt
  40.     return dist
  41.  
  42.  
  43. case = 0
  44. while True:
  45.     case += 1
  46.     n, m = map(int, input().split())
  47.     if n == m == 0:
  48.         break
  49.  
  50.     graph = [[10e310] * n for _ in range(n)]
  51.     for i in range(n):
  52.         graph[i][i] = 0
  53.  
  54.     for _ in range(m):
  55.         x, y = map(int, input().split())
  56.         graph[x - 1][y - 1] = 1
  57.     floyd_warshall(graph)
  58.     if graph[0][1] == 10e310 or graph[1][0] == 10e310:
  59.         print("Network {}\nImpossible\n".format(case))
  60.         continue
  61.     res = dijkstra(graph, (0, 0))
  62.     print("Network {}\nMinimum number of nodes = {}\n".format(case, res[(1, 1)]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement