现在小学的数学题目也不是那么好玩的。
看看这个寒假作业:
每个方块代表1~13中的某一个数字,但不能重复。
比如:
你一共找到了多少种方案?
看看这个寒假作业:
![](http://oj.ecustacm.cn/upload/image/20191117/20191117024258_22562.jpg)
每个方块代表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
你一共找到了多少种方案?
输出
请填写表示方案数目的整数。
【方法一】
用 stl 中的next_permutation函数,全排列,然后判断是否符合情况,符合则++
#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。递归深度为方格的个数,每个方格填数有13种选择:1-13,递归出口为填完第12个方格,判断条件是满足运算
#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; }