- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 85 lines of Python from the credited upstream file abc369_e.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def warshall_floyd(dist):5 """6 Args:7 Distance matrix between two points.8 9 Returns:10 Matrix of shortest distance.11 12 Landau notation: O(n ** 3).13 """14 15 v_count = len(dist[0])16 17 for k in range(v_count):18 for i in range(v_count):19 for j in range(v_count):20 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])21 22 return dist23 24 25def main():26 import sys27 from itertools import permutations, product28 29 input = sys.stdin.readline30 31 n, m = map(int, input().split())32 inf = 10**1833 graph = [[inf for _ in range(n)] for _ in range(n)]34 35 36 for i in range(n):37 graph[i][i] = 038 39 uvt = list()40 41 for _ in range(m):42 ui, vi, ti = map(int, input().split())43 ui -= 144 vi -= 145 uvt.append((ui, vi, ti))46 graph[ui][vi] = min(graph[ui][vi], ti)47 graph[vi][ui] = min(graph[vi][ui], ti)48 49 50 dist = warshall_floyd(graph)51 52 q = int(input())53 54 55 for _ in range(q):56 ki = int(input())57 b = list(map(lambda x: int(x) - 1, input().split()))58 ans = inf59 60 for pattern in permutations(b):61 for bit in range(1 << ki):62 prev_vi = 063 cost = 064 65 for i, pi in enumerate(pattern):66 ui, vi, ti = uvt[pi]67 68 if (bit >> i) & 1:69 ui, vi = vi, ui70 71 cost += dist[prev_vi][ui]72 cost += ti73 74 prev_vi = vi75 76 cost += dist[prev_vi][n - 1]77 78 ans = min(ans, cost)79 80 print(ans)81 82 83if __name__ == "__main__":84 main()85