nwerc-082 vor 3 Jahren
Ursprung
Commit
3906594b73
1 geänderte Dateien mit 42 neuen und 0 gelöschten Zeilen
  1. 42
    0
      I.py

+ 42
- 0
I.py Datei anzeigen

@@ -0,0 +1,42 @@
from __future__ import print_function
import heapq, sys

def dijkstra(G, s):
V, E = G; d = {}; S = set(); q = []
for u in V: d.setdefault(u, None)
for u in s:
d[u] = 0; heapq.heappush(q, (0,u))
while q:
n, u = heapq.heappop(q)
if u in S: continue
S.add(u)
for v in E[u]:
if d[v] is None or d[v] > d[u] + 1:
d[v] = d[u] + 1; heapq.heappush(q, (d[v],v))
return d

def transpose(G):
V, E = G; ET = {}
for u in V: ET[u] = []
for u, vs in E.iteritems():
for v in vs: ET[v].append(u)
return V, ET

n, m, k = map(int, sys.stdin.readline().split())
iron = [ int(x)-1 for x in sys.stdin.readline().split() ]
coal = [ int(x)-1 for x in sys.stdin.readline().split() ]
V, E = range(n), {}
for i, line in enumerate(sys.stdin):
E[i] = [ int(x)-1 for x in line.split()[1:] ]
G = V, E
GT = transpose(G)
ds = dijkstra(G, [0])
di = dijkstra(GT, iron)
dc = dijkstra(GT, coal)
try:
m = min( ds[i]+di[i]+dc[i] for i in xrange(n)
if None not in (ds[i],di[i],dc[i]) )
print(m)
except ValueError as e:
if "empty" not in e.args[0]: raise
print("impossible")

Laden…
Abbrechen
Speichern