- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 57 lines of Python from the credited upstream file abc375_e.py.
- The implementation visibly relies on ordered lookup, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 main():5 import sys6 7 input = sys.stdin.readline8 9 n = int(input())10 ab = [tuple(map(int, input().split())) for _ in range(n)]11 x = 012 13 for _, bi in ab:14 x += bi15 16 if x % 3 != 0:17 print(-1)18 exit()19 20 x = 321 22 23 inf = 10**1224 dp = [[inf for _ in range(x + 1)] for _ in range(x + 1)]25 dp[0][0] = 026 27 for ai, bi in ab:28 ndp = [[inf for _ in range(x + 1)] for _ in range(x + 1)]29 30 31 cost1 = 0 if ai == 1 else 132 cost2 = 0 if ai == 2 else 133 cost3 = 0 if ai == 3 else 134 35 36 for j1 in range(x + 1):37 for j2 in range(x + 1):38 nj1, nj2 = j1 + bi, j2 + bi39 40 if nj1 <= x:41 ndp[nj1][j2] = min(ndp[nj1][j2], dp[j1][j2] + cost1)42 if nj2 <= x:43 ndp[j1][nj2] = min(ndp[j1][nj2], dp[j1][j2] + cost2)44 45 ndp[j1][j2] = min(ndp[j1][j2], dp[j1][j2] + cost3)46 47 dp = ndp[:]48 49 if dp[x][x] == inf:50 print(-1)51 else:52 print(dp[x][x])53 54 55if __name__ == "__main__":56 main()57