ABC147 E - Balanced Path
https://atcoder.jp/contests/abc147/tasks/abc147_e (opens in a new tab)
้่ฒไธไฝใDPใ
็ฅ่ฆ ๅฎๆฐๅ้ซ้ๅ bitset
Python ใฏๅคๅ้ทๆผ็ฎใใตใใผใใใใฆใใใใใๆดๆฐๅใซๅฏพใใฆใใใๆผ็ฎใๅฉ็จใงใใใ
ใใใใใใซๅฏพใใฆbit << i & 1
ใ1
ใฎใจใใ่ฆ็ด i
ใๅซใใใจใซใใใจใใใจใใฐ ใฏใ่ฆ็ด ใจใใฆ ใๅซใใใจใซใชใใ
ใใฎๆ็นใงใจใใใๅๅคใซๅฏพใใฆใๅทฎใ ๅขๅ ใใใจใฏใๅฏพๅฟใใใใใใๅทฆใซ ๅใทใใใใใใใจใจ็ญใใใๆธๅฐใใๅ ดๅใฏๅณใทใใใใใใจใจ็ญใใใ
ใใคใในใฎๅคใใจใใใใใใไบใๅณใซใทใใใใฆใใใๆๅพใซใใฎๅๅทฆใทใใใใใฐใใใ
ใใพใใซๅคงใใใใๆฐใๆฑใใใจใซใชใใใใๅฎๆฐๅใๅคงใใใชใใใใชใใฎใใจใใ็นใซใฏ็ๅใๆฎใใ
MAX_DIFF = 15000
h, w = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(h)]
b = [list(map(int, input().split())) for _ in range(h)]
dp = [[0 for _ in range(w)] for _ in range(h)]
dp[0][0] |= 1 << (MAX_DIFF + a[0][0] - b[0][0])
dp[0][0] |= 1 << (MAX_DIFF + b[0][0] - a[0][0])
for i in range(h):
for j in range(w):
if i + 1 < h:
diff = abs(a[i + 1][j] - b[i + 1][j])
dp[i + 1][j] |= dp[i][j] << diff
dp[i + 1][j] |= dp[i][j] >> diff
if j + 1 < w:
diff = abs(a[i][j + 1] - b[i][j + 1])
dp[i][j + 1] |= dp[i][j] << diff
dp[i][j + 1] |= dp[i][j] >> diff
ans = MAX_DIFF
for i in range(2 * MAX_DIFF):
if dp[-1][-1] >> i & 1:
ans = min(ans, abs(i - MAX_DIFF))
print(ans)