Project Euler 61
Project Euler 61
题目
Cyclical figurate numbers
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:
| Triangle | $P_{3,n}=\dfrac{n(n+1)}{2}$ | $1, 3, 6, 10, 15, \dots$ |
| Square | $P_{4,n}=n^2$ | $1, 4, 9, 16, 25, \dots$ |
| Pentagonal | $P_{5,n}=\dfrac{n(3n−1)}{2}$ | $1, 5, 12, 22, 35, \dots$ |
| Hexagonal | $P_{6,n}=n(2n−1)$ | $1, 6, 15, 28, 45, \dots$ |
| Heptagonal | $P_{7,n}=\dfrac{n(5n−3)}{2}$ | $1, 7, 18, 34, 55, \dots$ |
| Octagonal | $P_{8,n}=n(3n−2)$ | $1, 8, 21, 40, 65, \dots$ |
The ordered set of three $4$-digit numbers: $8128, 2882, 8281$, has three interesting properties.
- The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
- Each polygonal type: triangle ($P{3,127}=8128$), square ($P{4,91}=8281$), and pentagonal ($P_{5,44}=2882$), is represented by a different number in the set.
- This is the only set of $4$-digit numbers with this property.
Find the sum of the only ordered set of six cyclic $4$-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
解决方案
以题目中的例子$8128, 2882, 8281$说明。
先将$6$个公式中的每一个$4$位数拆分成两块,如$[(81,28),(28,82),(82,81)]$,然后用前一块对应后一块的列表进行存储。
用二进制状态压缩递推(动态规划进行存储)。状态$f(s,i,j),(0<s<2^6,0\le i,j< 100)$表示在使用了一部分的公式下(用$6$比特的$s$表示),序列第一项的前一块为$i$,最后一项的后一块为$j$的情况下,整个序列里面前面一块的和。
序列里所有元素前面一块之和乘$101$就是答案。如$(81+28+82)\times 101$.
由于这个序列是环形的,因此一开始先假设第$0$个公式被使用了。因此,状态值$s$第$0$比特为$0$时,视为不合法状态。
最后答案为$f(2^6-1,i,i)\times 101$。其中$f(2^6-1,i,i)>0,0\leq i < 100$。
具体的转移过程请参考代码。
代码
1 | N = 100 |