标题:六角填数
下图所示六角形中,填入1~12的数字。
使得每条直线上的数字之和都相同。
图中,已经替你填好了3个数字,请你计算星号位置所代表的数字是多少?
蓝桥杯填空题只要结果。
方法一:直接暴力
#include "cstdio"
#include "cstring"
#include "iostream"
#include "algorithm"
using namespace std;
int main (){
int a[13];
for(int i=0;i<12;++i)
a[i]=i+1;
while(next_permutation(a,a+12)){
int t=a[1]+a[2]+a[3]+a[4];
if(a[0]==1 && a[1]==8 && a[11]==3 && t==a[0]+a[2]+a[5]+a[7] && t==a[0]+a[3]+a[6]+a[10] && t==a[7]+a[8]+a[9]+a[10] &&
(a[1]+a[5]+a[8]+a[11])==(a[4]+a[6]+a[9]+a[11]))
printf("%d\n",a[5]);
}
return 0;
}
方法二:DFS
#include <cstdio>
#include <cstring>
int a[12];
bool vis[12];
void dfs(int k){
int i;
int t=a[1]+a[2]+a[3]+a[4];
if(k==12 && a[0]==1 && a[1]==8 && a[11]==3
&& t==a[0]+a[2]+a[5]+a[7]
&& t==a[0]+a[3]+a[6]+a[10]
&& t==a[1]+a[5]+a[8]+a[11]
&& t==a[4]+a[6]+a[9]+a[11]
&& t==a[7]+a[8]+a[9]+a[10]
&& a[7]+a[8]+a[9]+a[10]==a[0]+a[3]+a[6]+a[10]){
printf("%d\n",a[5]);
return ;
}
for(i=1;i<=12;++i){
if(!vis[i]){
vis[i]=1;
a[k]=i;
dfs(k+1);
vis[i]=0;
a[k]=0;
}
}
}
int main (){
memset(vis,0,sizeof(vis));
memset(a,0,sizeof(a));
dfs(0);
return 0;
}