WA代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20;
int n,m,res = 0,a,b;
bool st[N];
void dfs(int x)
{
int tmp = m;
while (tmp)
{
st[tmp % 10] = true;
tmp /= 10;
}
if (x > 4)
{
for (int i = 1; i <= 9; i++)
{
if (!st[i])
b = b * 10 + i;
}
if ((n - m)*a == b &&!st[b] && !st[a])
res++;
a = 0,b = 0;
return;
}
for (int i = 1; i <= 9; i++)
{
if (!st[i])
{
st[i] = true;
a = a * 10 + i;
dfs(x + 1);
a -= i;
st[i] = false;
}
}
}
int main()
{
cin >> n;
for (int i = 1; i < n; i++)
{
m = n - i;
dfs(1);
}
cout << res << endl;
return 0;
}
AC代码
思路:枚举全排列
枚举位数,插版法 a|b|c
计算 n = a + b/c
//枚举全排列
//枚举位数,插版法 a|b|c
//计算
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000010;
int n, m, res = 0, a, b;
bool st[N];
int arr[N];
int clac(int l, int r)
{
int sum = 0;
for (int i = l; i <= r; i++)
sum = sum * 10 + arr[i];
return sum;
}
void dfs(int x)
{
if (x > 9)
{
for (int i = 1;i <= 7;i++)
for (int j = i + 1; j <= 8; j++)
{
int a = clac(1, i);
int b = clac(i + 1, j);
int c = clac(j + 1, 9);
if (c * n == a * c + b) res++;
}
return;
}
for (int i = 1; i <= 9; i++)
{
if (!st[i])
{
arr[x] = i;
st[i] = true;
dfs(x + 1);
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(1);
cout << res << endl;
return 0;
}
优化
枚举a,对于每一个a枚举c,对于每一个a,c算b是否合法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20;
int n, res = 0;
bool st[N];
bool backup[N];
bool check(int a, int c)
{
long long b = (long long)c * n - a * c;
if (!a || !c || !b) return false;
memcpy(backup, st, sizeof st);
while (b)
{
int x = b % 10;
b /= 10;
if (!x || backup[x]) return false;
backup[x] = true;
}
for (int i = 1; i <= 9; i++)
if (!backup[i]) return false;
return true;
}
void dfs_c(int x, int a, int c)
{
if (x >= 9) return;
if (check(a, c)) res++;
for (int i = 1; i <= 9; i++)
{
if (!st[i])
{
st[i] = true;
dfs_c(x + 1, a, c * 10 + i);
st[i] = false;
}
}
}
void dfs_a(int x, int a)
{
if (a >= n) return;
if (a) dfs_c(x, a, 0);
for (int i = 1; i <= 9; i++)
{
if (!st[i])
{
st[i] = true;
dfs_a(x + 1, a * 10 + i);
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs_a(0, 0);
cout << res << endl;
return 0;
}