- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 63 lines of Python from the credited upstream file abc371_c.py.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 read_graph(n):5 from collections import defaultdict6 7 m = int(input())8 g = defaultdict(bool)9 10 for i in range(n):11 for j in range(n):12 g[(i, j)] = False13 14 for _ in range(m):15 ui, vi = map(int, input().split())16 ui -= 117 vi -= 118 19 g[(ui, vi)] = True20 g[(vi, ui)] = True21 22 return g23 24 25def main():26 import sys27 from collections import defaultdict28 from itertools import permutations29 30 input = sys.stdin.readline31 32 n = int(input())33 g = read_graph(n)34 h = read_graph(n)35 36 a = defaultdict(int)37 38 for i in range(n - 1):39 ai = list(map(int, input().split()))40 41 for j, aij in enumerate(ai, i + 1):42 a[(i, j)] = aij43 a[(j, i)] = aij44 45 inf = 10**1846 ans = inf47 48 for pattern in permutations(range(n)):49 cost = 050 51 for i in range(n):52 for j in range(i + 1, n):53 if h[(i, j)] != g[(pattern[i], pattern[j])]:54 cost += a[(i, j)]55 56 ans = min(ans, cost)57 58 print(ans)59 60 61if __name__ == "__main__":62 main()63