凑算式
B DEF
A + --- + ------- = 10
C GHI
(如果显示有问题,可以参见【图1.jpg】)
这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。
比如:
6+8/3+952/714 就是一种解法,
5+3/1+972/486 是另一种解法。
这个算式一共有多少种解法?
注意:你提交应该是个整数,不要填写任何多余的内容或说明性文字。
第一种写法用DFS
#include <iostream>
#include <cstring>
using namespace std;
int num[10];
int vis[10];
int n, cnt;
int a, b, c, def, ghi;
//不重复全排列
//a + b/c + def/ghi = 10 转化为 b*ghi + def*c = (10-a)*c*ghi
//避免误差
void dfs(int r) {
// cout << r << endl;
if (r == 10) { // 到第10位结束
a = num[1];
b = num[2];
c = num[3];
def = num[4]*100 + num[5]*10 + num[6];
ghi = num[7]*100 + num[8]*10 + num[9];
if (b*ghi + def*c == (10-a)*c*ghi) {
cnt ++;
}
return;
}
for (int i = 1; i <= 9; i++) {
if (!vis[i]) {
vis[i] = 1;
num[r] = i;
dfs(r+1);
vis[i] = 0;
}
}
return;
}
int main() {
dfs(1); // 从第1位开始
cout << cnt << endl;
return 0;
}
第二种写法用next_permutation()
#include <iostream>
#include <algorithm>
using namespace std;
int ans;
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
bool check() {
int x = a[3]*100 + a[4]*10 + a[5];
int y = a[6]*100 + a[7]*10 + a[8];
if ((a[1]*y + a[2]*x) == ((10-a[0])*a[2]*y))
return true;
return false;
}
int main() {
sort(a, a + 9);
do {
if (check()) {
ans++;
}
} while (next_permutation(a, a + 9));
cout << ans << endl;
return 0;
}