六角填数
如图所示六角形中,填入1~12的数字。
使得每条直线上的数字之和都相同。
图中,已经替你填好了3个数字,请你计算星号位置所代表的数字是多少?
暴力伤肾啊~~
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <iostream>
#include <cstring>
using namespace std;
int check(int x,int y,int z,int k,int h,int l)
{
if(x==y&&x==z&&x==k&&x==h&&x==l)
return 1;
else return 0;
}
int main()
{
int i1=1,i2=8,i12=3;
for(int i3=2; i3<=12; i3++)
{
if(i3==8||i3==3)continue;
for(int i4=2; i4<=12; i4++)
{
if(i4==8||i4==3)continue;
for(int i5=2; i5<=12; i5++)
{
if(i5==8||i5==3)continue;
for(int i6=2; i6<=12; i6++)
{
if(i6==8||i6==3)continue;
for(int i7=2; i7<=12; i7++)
{
if(i7==8||i7==3)continue;
for(int i8=2; i8<=12; i8++)
{
if(i8==8||i8==3)continue;
for(int i9=2; i9<=12; i9++)
{
if(i9==8||i9==3)continue;
for(int i10=2; i10<=12; i10++)
{
if(i10==8||i10==3)continue;
for(int i11=2; i11<=12; i11++)
{
if(i11==8||i11==3)continue;
if(
i3!=i4&&i3!=i5&&i3!=i6&&i3!=i7&&i3!=i8&&i3!=i9&&i3!=i10&&i3!=i11&&
i4!=i5&&i4!=i6&&i4!=i7&&i4!=i8&&i4!=i9&&i4!=i10&&i4!=i11&&
i5!=i6&&i5!=i7&&i5!=i8&&i5!=i9&&i5!=i10&&i5!=i11&&
i6!=i7&&i6!=i8&&i6!=i9&&i6!=i10&&i6!=i11&&
i7!=i8&&i7!=i9&&i7!=i10&&i7!=i11&&
i8!=i9&&i8!=i10&&i8!=i11&&
i9!=i10&&i9!=i11&&
i10!=i11)
{
int n1=i1+i3+i6+i8;
int n2=i1+i4+i7+i11;
int n3=i2+i3+i4+i5;
int n4=i2+i6+i9+i12;
int n5=i5+i7+i10+i12;
int n6=i8+i9+i10+i11;
if(check(n1,n2,n3,n4,n5,n6))
{
printf("%d %d %d %d %d %d %d %d %d %d %d %d\n",i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12);
return 0;
}
}
}
}
}
}
}
}
}
}
}
}
还是dfs好
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define eps 10e-10
#define N 15
int a[N];
bool vis[N];
void dfs(int x){
if(x == 1 || x == 2 || x == 12){
dfs(x+1);
return ;
}
if(x > 12){
int t[6];
t[0] = a[1] + a[3] + a[6] + a[8];
t[1] = a[1] + a[4] + a[7] + a[11];
t[2] = a[2] + a[3] + a[4] + a[5];
t[3] = a[2] + a[6] + a[9] + a[12];
t[4] = a[8] + a[9] + a[10] + a[11];
t[5] = a[12] + a[10] + a[7] + a[5];
for(int i = 1; i < 6; ++i){
if(t[i] != t[i-1])return ;
}
cout<<a[6]<<endl;
return ;
}
for(int i = 1;i < 13; ++i){
if(!vis[i]){
vis[i] = 1;
a[x] = i;
dfs(x+1);
vis[i] = 0;
}
}
}
int main(){
memset(vis,0,sizeof(vis));
vis[1] = 1;
a[1] = 1;
vis[8] = 1;
a[2] = 8;
vis[3] = 1;
a[12] =3;
dfs(1);
return 0;
}