2016蓝桥杯省赛C/C++A组第六题 寒假作业

时间:2022-06-10 08:47:57

题意:现在小学的数学题目也不是那么好玩的。 
看看这个寒假作业: 
□ + □ = □ 
□ - □ = □ 
□ × □ = □ 
□ ÷ □ = □ 
每个方块代表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 
就算两种解法。(加法,乘法交换律后算不同的方案) 
你一共找到了多少种方案?

分析:回溯即可,但是如果等到cur==12再统一判断,时间复杂度会达到2的13次方,非常慢,所以当一个式子填完后立即判断,不满足则立即返回。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define lowbit(x) (x & (-x))
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 100 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int vis[15];
int a[15];
int ans;
void dfs(int cur){
if(cur == 3){
if(a[0] + a[1] != a[2]) return;
}
if(cur == 6){
if(a[3] - a[4] != a[5]) return;
}
if(cur == 9){
if(a[6] * a[7] != a[8]) return;
}
if(cur == 12){
if(a[10] * a[11] == a[9]){
++ans;
}
return;
}
for(int i = 1; i <= 13; ++i){
if(vis[i]) continue;
vis[i] = 1;
a[cur] = i;
dfs(cur + 1);
a[cur] = 0;
vis[i] = 0;
}
}
int main(){
dfs(0);
printf("%d\n", ans);
return 0;
}