Fill in the numbers from 1 to 12 in the hexagon as shown. Make the sum of the numbers on each line the same.
In the picture, 3 numbers have been filled in for you. Can you calculate the number represented by the position of the asterisk?
Method 1: dfs
#include<iostream>
#include<cstring>#include<cstdio>
#include<algorithm>
using namespace std;
int a[13],book[13]; //the a array is used to store the numbers inside the circle
// the book array is used to mark 1- 12 numbers to prevent repetition
void dfs(int x) //x represents the subscript of the a array, starting from zero
{
int i;
if(x==1||x==2||x==12)
{
dfs(x+1);
return;
}
if(x==13) //After filling in 12 numbers, determine whether the conditions are met
{
int b[6];
b[0]=a[1]+a[3 ]+a[6]+a[8];
b[1]=a[1]+a[4]+a[7]+a[11];
b[2]=a[2]+a[3 ]+a[4]+a[5];
b[3]=a[2]+a[6]+a[9]+a[12];
b[4]=a[5]+a[7 ]+a[10]+a[12];
b[5]=a[8]+a[9]+a[10]+a[11];
for(i=0;i<5;i++)
{
if(b[i]!=b[i+1])
{
return; } } cout<<a[6]; } for(i=1;i<13;i++) { if(book[i]==0) //判断i是否未使用过 { book[i]=1; //标记 a[x]=i; dfs(x+1); book[i]=0; //取消标记 } } } int main() { a[1]=1;a[2]=8;a[12]=3; book[1]=1;book[8]=1;book[3]=1; dfs(1); return 0;
}
Method 2: Full permutation function
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int a[13]={0,1,3,8,2,4,5,6,7,9,10,11,12};
sort(a+1,a+13);
do
{
int b[6],f=1;
b[0]=a[1]+a[3]+a[6]+a[8];
b[1]=a[1]+a[4]+a[7]+a[11];
b[2]=a[2]+a[3]+a[4]+a[5];
b[3]=a[2]+a[6]+a[9]+a[12];
b[4]=a[5]+a[7]+a[10]+a[12];
b[5]=a[8]+a[9]+a[10]+a[11];
for(int i=0;i<5;i++)
{
if(b[i]!=b[i+1])
{
f=0;
break; } } if(f==0) continue; else {
cout<<a[6];break; }}while(next_permutation(a+1,a+13)); return 0;}