题目描述
观察如下的算式:9213 x 85674 = 789314562
左边的乘数和被乘数正好用到了1~9的所有数字,每个1次。
而乘积恰好也是用到了1~9的所有数字,并且每个1次。
请你借助计算机的强大计算能力,找出满足如上要求的9数算式一共有多少个?
注意:
1. 总数目包含题目给出的那个示例。
2. 乘数和被乘数交换后作为同一方案来看待。
输出
输出一个整数表示答案
代码如下:
#include <iostream>
using namespace std;
const int N = 12;
bool vis[N];
int ans = 0;
int book[N];bool check2() {for (int i = 1; i <= 9; i++) {if (book[i] != 1) {for (int i = 1; i <= 9; i++) {book[i] = 0;}return false;}}for (int i = 1; i <= 9; i++) {book[i] = 0;//这一步容易忽略,就因为忽略了这个,耽误了我30分钟........}return true;
}bool check(int suma, int sumc) {long long sum = (long long)suma * sumc;while (sum) {book[sum % 10]++;sum = sum / 10;}if (check2()) {return true;}return false;
}void dfs_c(int u, int suma, int sumc) {if (u > 9) {return;}if (check(suma, sumc) && sumc != 0) {ans++;}for (int i = 1; i <= 9; i++) {if (!vis[i]) {vis[i] = true;dfs_c(u + 1, suma, sumc * 10 + i);vis[i] = false;}}
}void dfs_a(int u, int suma) {dfs_c(u, suma, 0);for (int i = 1; i <= 9; i++) {if (!vis[i]) {vis[i] = true;dfs_a(u + 1, suma * 10 + i);vis[i] = false;}}
}int main() {dfs_a(0, 0);cout << ans / 2 << endl;//乘数和被乘数交换后作为同一方案来看待,所以要除2return 0;
}
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 15;
bool vis[N];
int ans;bool check_2(LL sumb) {bool st[N];for (int i = 1; i <= 9; i++) {st[i] = 0;}while (sumb) {st[sumb % 10] = true;sumb = sumb / 10;}bool flag = false;for (int i = 1; i <= 9; i++) {if (!st[i]) {return false;}}return true;
}bool check_1(int suma, int sumc) {LL sumb = (LL)suma * sumc;if (check_2(sumb)) {return true;}return false;
}void dfs_c(int u, int suma, int sumc) {if (u > 9) {return ;}if (check_1(suma, sumc) ) {ans++;return ;}for (int i = 1; i <= 9; i++) {if (!vis[i]) {vis[i] = true;dfs_c(u + 1, suma, sumc * 10 + i);vis[i] = false;}}
}void dfs_a(int u, int suma) {dfs_c(u, suma, 0);for (int i = 1; i <= 9; i++) {if (!vis[i]) {vis[i] = true;dfs_a(u + 1, suma * 10 + i);vis[i] = false;}}
}int main() {dfs_a(0, 0);cout << ans / 2 << endl;return 0;
}