第一次做,使用全排列
1.先全排列1~9
2.再分别枚举a,b,c
3.最后判断等式是否成立
问题:耗时有点久
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
int res;
bool st[N];
int path[N];
/*function:求解分割后的数值大小
*param l: 枚举数值的左边界
*param r: 枚举数值的右边界
*return : 枚举的数值
*/
int get(int l, int r)
{
int m = 0;
for (int i = l; i <= r; i++) {
m = m * 10 + path[i];
}
return m;
}
/*funcion: 检查等式是否成立
* param a: 数值a
param b: 数值b
param c: 数值c
*/
bool check(int a, int b, int c)
{
if ((n * c - a * c) == b) return true;
return false;
}
void dfs(int u)
{
if (u >= N) { //已经完成全排列,用双重循环将全排列划分为三个数字, 即分别枚举a,b,c三个数值
for (int i = 1; i <= 7; i++) {
for (int j = i + 1; j <= 8; j++) {
int a = get(1, i); //分别将a b c的数值表示出来
int b = get(i + 1, j);
int c = get(j + 1, 9);
if (check(a, b, c)) res++; //判断是否符合题目条件
}
}
return;
}
for (int i = 1; i < N; i++) {
if (!st[i]){
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
path[u] = 0;
}
}
}
int main()
{
cin >> n;
dfs(1);
cout << res << endl;
return 0;
}