五星填数。

 在五星图案节点填上数字: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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值