from copy import deepcopy
def main(h, w):
global cnt
cnt = 0
def rec(i, h, w):
r, c = divmod(i, 3)
if i == 8 and h[r] == w[c]:
global cnt
cnt += 1
else:
if c == 2:
v = h[r]
if w[c] - v < (2-r): return
available = [v]
elif r == 2:
v = w[c]
if h[r] - v < (2-c): return
available = [v]
else:
available = range(1, min(h[r] - (2-c), w[c] - (2-r)) + 1)
for av in available:
h = deepcopy(h)
h[r] -= av
w = deepcopy(w)
w[c] -= av
rec(i+1, h, w)
rec(0, h, w)
return cnt
テストデータ・テスト関数定義↓
# 縮小表示
test_data = [
{
"in":[[3, 4, 6], [3, 3, 7]],
"out": 1
},{
"in":[[3, 4, 5], [6, 7, 8]],
"out": 0
},{
"in":[[5, 13, 10], [6, 13, 9]],
"out": 120
},{
"in":[[20, 25, 30], [22, 29, 24]],
"out": 30613
},
]
def test_all(f):
for i, data in enumerate(test_data):
exp = data["out"]
ans = f(*data["in"])
result = "AC" if exp == ans else "WA"
print(f"{i+1} {result}: expected: {exp}, output: {ans}")test_all(main)
from copy import deepcopy
def main2(h, w):
global cnt
cnt = 0
def rec(i, h, w):
r, c = divmod(i, 3)
if i == 8 and h[r] == w[c]:
global cnt
cnt += 1
else:
if c == 2:
v = h[r]
if w[c] - v < (2-r): return
available = [v]
elif r == 2:
v = w[c]
if h[r] - v < (2-c): return
available = [v]
else:
available = range(1, min(h[r] - (2-c), w[c] - (2-r)) + 1)
for av in available:
new_h = deepcopy(h)
new_h[r] -= av
new_w = deepcopy(w)
new_w[c] -= av
rec(i+1, new_h, new_w)
rec(0, h, w)
return cnt
diff ↓
# 縮小表示
from difflib import HtmlDiff as diff
str_main1 = '''
from copy import deepcopy
def main(h, w):
global cnt
cnt = 0
def rec(i, h, w):
r, c = divmod(i, 3)
if i == 8 and h[r] == w[c]:
global cnt
cnt += 1
else:
if c == 2:
v = h[r]
if w[c] - v < (2-r): return
available = [v]
elif r == 2:
v = w[c]
if h[r] - v < (2-c): return
available = [v]
else:
available = range(1, min(h[r] - (2-c), w[c] - (2-r)) + 1)
for av in available:
h = deepcopy(h)
h[r] -= av
w = deepcopy(w)
w[c] -= av
rec(i+1, h, w)
rec(0, h, w)
return cnt
'''.splitlines()
str_main2 = '''
from copy import deepcopy
def main(h, w):
global cnt
cnt = 0
def rec(i, h, w):
r, c = divmod(i, 3)
if i == 8 and h[r] == w[c]:
global cnt
cnt += 1
else:
if c == 2:
v = h[r]
if w[c] - v < (2-r): return
available = [v]
elif r == 2:
v = w[c]
if h[r] - v < (2-c): return
available = [v]
else:
available = range(1, min(h[r] - (2-c), w[c] - (2-r)) + 1)
for av in available:
new_h = deepcopy(h)
new_h[r] -= av
new_w = deepcopy(w)
new_w[c] -= av
rec(i+1, new_h, new_w)
rec(0, h, w)
return cnt
'''.splitlines()
diff().make_file(str_main1, str_main2)test_all(main2)
def main3(h, w):
global cnt
cnt = 0
m = [[0]*3 for _ in range(3)]
def rec(i):
r, c = divmod(i, 3)
if i == 9:
if sum([r[2] for r in m]) == w[2]:
global cnt
cnt += 1
else:
if c == 2:
v = h[r] - (m[r][0] + m[r][1])
if v < 1: return
available = [v]
elif r == 2:
v = w[c] - (m[0][c] + m[1][c])
if v < 1: return
available = [v]
else:
available = range(1, min(h[r] - (2-c), w[c] - (2-r)) + 1)
for av in available:
m[r][c] = av
rec(i+1)
rec(0)
return cnttest_all(main3)