[蓝桥杯2016初赛]寒假作业

题目链接:http://oj.ecustacm.cn/problem.php?id=1285

题目描述

现在小学的数学题目也不是那么好玩的。
看看这个寒假作业:

每个方块代表1~13中的某一个数字,但不能重复。
比如:
6  + 7 = 13
9  - 8 = 1
3  * 4 = 12
10 / 2 = 5
以及: 
7  + 6 = 13
9  - 8 = 1
3 * 4 = 12
10 / 2 = 5
就算两种解法。(加法,乘法交换律后算不同的方案)
你一共找到了多少种方案?

输出

请填写表示方案数目的整数。
 
 
思路:
别想太多,暴力的去跑。
迟早答案会跑出来的
 
#include<iostream>
#include<ctime>
#include<cmath>
#include<bits/stdc++.h>
using namespace std;
bool f(int a[]){
    if(a[0]+a[1]!=a[2])
        return false;
    if(a[3]-a[4]!=a[5])
        return false;
    if(a[6]*a[7]!=a[8])
        return false;
    if(a[9]!=a[10]*a[11])
        return false;
    return true;
}
int main()
{
   int a[13] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
   int ans = 0;
   do{
       if(f(a))
            ans++;
   }while(next_permutation(a,a+13));//全排列函数 
   cout<<ans<<endl;
   cout << clock() << "ms" << endl;//看看跑了多长时间 
}

DFS 的话就快很多了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
 
int vis[15];
int a[15];
int ans = 0;
void dfs(int k)
{
    if(k == 13)
    {
        if(a[10] == a[11]*a[12])
        ans++;
        return ;
    }
    if(k == 4)
    {
        if(a[1] + a[2] != a[3])
            return;
    }
    if(k == 7)
    {
        if(a[4] - a[5] != a[6])
            return;
    }
    if(k == 10)
    {
        if(a[7] * a[8] != a[9])
            return ;
    }
    for(int i = 1; i <= 13; i++)
    {
        if(!vis[i])
        {
            vis[i] = 1;
            a[k] = i;
            dfs(k+1);
            vis[i] = 0;
        }
    }
}
int main()
{
    dfs(1);
    cout<<ans<<endl; 
    return 0;
}
原文地址:https://www.cnblogs.com/-Ackerman/p/12241214.html