๐Ÿšง This website is under construction. ๐Ÿšง
AtCoder
ABC
147
E

bitset
DP
ABC
E

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ใ‚’ๅซใ‚€ใ“ใจใซใ™ใ‚‹ใจใ€ใŸใจใˆใฐ 1001010(2)1001010_{(2)} ใฏใ€่ฆ็ด ใจใ—ใฆ 1,3,61,3,6 ใ‚’ๅซใ‚€ใ“ใจใซใชใ‚‹ใ€‚

ใใฎๆ™‚็‚นใงใจใ‚Šใ†ใ‚‹ๅ„ๅ€คใซๅฏพใ—ใฆใ€ๅทฎใŒ dd ๅข—ๅŠ ใ™ใ‚‹ใจใฏใ€ๅฏพๅฟœใ™ใ‚‹ใƒ“ใƒƒใƒˆใŒๅทฆใซ dd ๅˆ†ใ‚ทใƒ•ใƒˆใ•ใ‚Œใ‚‹ใ“ใจใจ็ญ‰ใ—ใใ€ๆธ›ๅฐ‘ใ™ใ‚‹ๅ ดๅˆใฏๅณใ‚ทใƒ•ใƒˆใ™ใ‚‹ใ“ใจใจ็ญ‰ใ—ใ„ใ€‚

ใƒžใ‚คใƒŠใ‚นใฎๅ€คใ‚’ใจใ‚Šใ†ใ‚‹ใŸใ‚ใ€ไบˆใ‚ๅณใซใ‚ทใƒ•ใƒˆใ—ใฆใŠใใ€ๆœ€ๅพŒใซใใฎๅˆ†ๅทฆใ‚ทใƒ•ใƒˆใ™ใ‚Œใฐใ‚ˆใ„ใ€‚

ใ‚ใพใ‚Šใซๅคงใใ™ใŽใ‚‹ๆ•ฐใ‚’ๆ‰ฑใ†ใ“ใจใซใชใ‚‹ใŸใ‚ใ€ๅฎšๆ•ฐๅ€ใŒๅคงใใใชใ‚Šใ™ใŽใชใ„ใฎใ‹ใจใ„ใ†็‚นใซใฏ็–‘ๅ•ใŒๆฎ‹ใ‚‹ใ€‚

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)