nwerc-082 vor 2 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 @@
1
+from __future__ import print_function
2
+import heapq, sys
3
+
4
+def dijkstra(G, s):
5
+  V, E = G; d = {}; S = set(); q = []
6
+  for u in V: d.setdefault(u, None)
7
+  for u in s:
8
+    d[u] = 0; heapq.heappush(q, (0,u))
9
+  while q:
10
+    n, u = heapq.heappop(q)
11
+    if u in S: continue
12
+    S.add(u)
13
+    for v in E[u]:
14
+      if d[v] is None or d[v] > d[u] + 1:
15
+        d[v] = d[u] + 1; heapq.heappush(q, (d[v],v))
16
+  return d
17
+
18
+def transpose(G):
19
+  V, E = G; ET = {}
20
+  for u in V: ET[u] = []
21
+  for u, vs in E.iteritems():
22
+    for v in vs: ET[v].append(u)
23
+  return V, ET
24
+
25
+n, m, k = map(int, sys.stdin.readline().split())
26
+iron    = [ int(x)-1 for x in sys.stdin.readline().split() ]
27
+coal    = [ int(x)-1 for x in sys.stdin.readline().split() ]
28
+V, E    = range(n), {}
29
+for i, line in enumerate(sys.stdin):
30
+  E[i] = [ int(x)-1 for x in line.split()[1:] ]
31
+G       = V, E
32
+GT      = transpose(G)
33
+ds      = dijkstra(G, [0])
34
+di      = dijkstra(GT, iron)
35
+dc      = dijkstra(GT, coal)
36
+try:
37
+  m = min( ds[i]+di[i]+dc[i] for i in xrange(n)
38
+           if None not in (ds[i],di[i],dc[i]) )
39
+  print(m)
40
+except ValueError as e:
41
+  if "empty" not in e.args[0]: raise
42
+  print("impossible")

Laden…
Abbrechen
Speichern