在五星图案节点填上数字:1~12, 不包括7和11。
要求每条直线上数字和相等。
请搜索所有可能的填法有多少种。
注意:旋转或镜像后相同的算同一种填法
如下图就是一个恰当的填法。
一、使用dfs算法
#include<iostream>
using namespace std;
const int N=10;
int star[N], num[N]={1, 2, 3, 4, 5, 6, 8, 9, 10, 12};
bool st[N];
int cnt=0, starcnt=0;
#define A star[0]+star[2]+star[5]+star[8]
#define B star[1]+star[2]+star[3]+star[4]
#define C star[0]+star[3]+star[7]+star[9]
#define D star[1]+star[5]+star[6]+star[9]
#define E star[4]+star[6]+star[7]+star[8]
void printstar()
{
cout << " " << star[0] << "\n";
cout << star[1] << " " << star[2] << " "<< star[3] << " " << star[4] << "\n";
cout << " " << star[5] << " " << star[7] << "\n";
cout << " " << star[6] << "\n";
cout << " " << star[8] << " " << star[9] << "\n\n\n";
return;
}
void dfs(int u)
{
if(u==N)
{
cnt++;
if((A==B) && (A==C) && (A==D) && (A==E))
{
printstar();
starcnt++;
}
return;
}
for(int i=0; i<N; i++)
{
if(!st[i])
{
st[i]=1;
star[u]=num[i];
dfs(u+1);
st[i]=0;
}
}
}
int main()
{
dfs(0);
cout << "total arrange =" << cnt << "\n";
cout << " star num=" << starcnt/10 << "\n";
return 0;
}
二、使用next_permutation()函数
#include<iostream>
#include<algorithm>
using namespace std;
const int N=10;
int star[N]={1, 2, 3, 4, 5, 6, 8, 9, 10, 12};
int cnt=0, starcnt=0;
#define A star[0]+star[2]+star[5]+star[8]
#define B star[1]+star[2]+star[3]+star[4]
#define C star[0]+star[3]+star[7]+star[9]
#define D star[1]+star[5]+star[6]+star[9]
#define E star[4]+star[6]+star[7]+star[8]
void printstar()
{
cout << " " << star[0] << "\n";
cout << star[1] << " " << star[2] << " "<< star[3] << " " << star[4] << "\n";
cout << " " << star[5] << " " << star[7] << "\n";
cout << " " << star[6] << "\n";
cout << " " << star[8] << " " << star[9] << "\n\n\n";
return;
}
int main()
{
do
{
cnt++;
if(A==B && A==C && A==D && A==E)
{
printstar();
starcnt++;
}
}while(next_permutation(star, star+ N));
cout << "total arrange =" << cnt << "\n";
cout << " star num=" << starcnt/10 << "\n";
return 0;
}