]> Skullheadx's Git Forge - CCC.git/commitdiff
Update S4.py
authorSkullheadx <admonty1@gmail.com>
Wed, 8 Feb 2023 22:27:36 +0000 (17:27 -0500)
committerSkullheadx <admonty1@gmail.com>
Wed, 8 Feb 2023 22:27:36 +0000 (17:27 -0500)
Main/Python/2021/S4.py

index 21c7901034081f2239b0a34104f2eb3abaa9d381..98cf4be61cb18c19353f1e2f44b0bc9f1b42b4a6 100644 (file)
 #
 #
 # """
+from queue import Queue
 
 
 def swap(i, j):
        stations[i], stations[j] = stations[j], stations[i]
 
 
-def get_next_station(m, station):
-       if m > len(stations) and station != N:
-               return False
-
-       if station == N:
-               outputs.append(m)
-               return True
-       # take a walkway
-       if station in walkways:
-               for destination in walkways[station]:
-                       get_next_station(m + 1, destination)
-
-       if m < len(stations):
-               train = stations[m]
-               # take a train
-               if train == station:
-                       if m < len(stations) - 1:
-                               get_next_station(m + 1, stations[m + 1])
-               # wait at the station
-               get_next_station(m + 1, station)
-
-
-
 N, W, D = tuple(map(int, input().split()))
 walkways = dict()
 for i in range(W):
        A, B = tuple(map(int, input().split()))
        walkways[A] = walkways.get(A, list()) + [B]
 
-outputs = []
-test = []
-
 stations = list(map(int, input().split()))
+
 for i in range(D):
        X, Y = tuple(map(int, input().split()))
-       swap(X - 1, Y - 1)
-       outputs.clear()
-       get_next_station(0, 1)
-       print(min(outputs))
\ No newline at end of file
+       swap(X-1, Y-1)
+
+
+
+       q = Queue()
+       q.put((0, 1))
+
+
+
+       visited = set()
+
+       while not q.empty():
+               m, station = q.get()
+
+               if (m, station) in visited:
+                       continue
+               visited.add((m, station))
+
+               if m > len(stations):
+                       continue
+
+               if station == N:
+                       print(m)
+                       break
+               # print(f"q:{q.qsize()}")
+
+               # take a walkway
+               if station in walkways:
+                       for destination in walkways[station]:
+                               q.put((m + 1, destination))
+
+               # take a train
+               if stations[m] == station and m + 1 < len(stations):
+                       q.put((m + 1, stations[m + 1]))
+               # wait at the station
+               q.put((m + 1, station))