Project Euler:Problem 68 Magic 5-gon ring

来源:互联网 发布:淘宝直播卖的东西质量 编辑:程序博客网 时间:2024/06/03 23:46

Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine.


Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), each solution can be described uniquely. For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.

It is possible to complete the ring with four different totals: 9, 10, 11, and 12. There are eight solutions in total.

TotalSolution Set94,2,3; 5,3,1; 6,1,294,3,2; 6,2,1; 5,1,3102,3,5; 4,5,1; 6,1,3102,5,3; 6,3,1; 4,1,5111,4,6; 3,6,2; 5,2,4111,6,4; 5,4,2; 3,2,6121,5,6; 2,6,4; 3,4,5121,6,5; 3,5,4; 2,4,6

By concatenating each group it is possible to form 9-digit strings; the maximum string for a 3-gon ring is 432621513.

Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16- and 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring?



最外圈的a0是最外圈里最小的数,所以a0<=6,同时要使得这个string最大,所以a0=6,同时最外圈的其他数分别为7,8,9,10。

1+2+3+...+9+10=55         内圈的数为1,2,3,4,5,算起来每一行的和都为14

所以a0所在的哪一行,其他两个数的和为8,而6,7都位于最外圈,所以这两个数只能是5和3


Data structure


#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;int main(){int a[7] = { 1, 2, 4, 7, 8, 9, 10 };int b[2] = { 3, 5 };string tmp,res;do{for (int i = 0; i < 2; i++){if (a[0] + b[i] + a[1] == 14 && a[1] + a[2] + a[3] == 14 && a[3] + a[4] + a[5] == 14 && a[5] + a[6] + b[(i + 1) % 2] == 14){cout << "6" << b[i] << b[(i + 1) % 2] << endl;cout << a[0] << b[(i + 1) % 2] << a[1] << endl;cout << a[2] << a[1] << a[3] << endl;cout << a[4] << a[3] << a[5] << endl;cout << a[6] << a[5] << b[i] << endl;cout << endl;}}} while (next_permutation(a, a + 7));system("pause");return 0;}


偷了个懒,输出两组结果



显然那个大的6531031914842725

0 0