首先生成所有的四位多边形数, 将它们按照类型存在六个字典中,字典的键值是其前两位数字。
接下来作深度优先搜索即得结果8256, 5625, 2512, 1281, 8128, 2882, 它们的和是$28684$。
d=[{},{},{},{},{},{}]
for n in range(200):
for i,t in enumerate([n*(n+1)/2, n*n, n*(3*n-1)/2, n*(2*n-1), n*(5*n-3)/2, n*(3*n-2)]):
if t>999 and t < 10000:
if t/100 in d[i]:
d[i][t/100].append(t%100)
else:
d[i][t/100]=[t%100]
t=[[[u*100+v],[1,2,3,4,5]] for u in d[0] for v in d[0][u]]
found=False
while not found:
s,c=t.pop()
if c:
z=s[-1]%100
for i in c:
if z in d[i]:
for y in d[i][z]:
t.append([s+[z*100+y],[j for j in c if j!=i]])
else:
if s[-1]%100==s[0]/100:
found=True
print sum(s),s
|