#include <bits/stdc++.h>
using namespace std;
const int N=100010;
int path[10];
bool vis[10];
int ans=0;
int backup[10];
int n;
int calc(int l, int r) {
int res = 0;
for (int i = l; i <= r; i++) {
res = res * 10 + path[i];
}
return res;
}
void dfs(int u)
{
if (u==10)
{
// for (int i=1;i<=9;i++) cout<<path[i]<<' ';
// cout<<endl;
memcpy(backup,path,sizeof(path));
// for (int i=1;i<=9;i++) path[i]+=path[i-1];
for (int i=1;i<=7;i++)
{
for (int j=i+1;j<=8;j++)
{
// int a=path[i],b=path[j]-path[i],c=path[9]-path[j];
// cout<<a<<' '<<b<<' '<<c<<endl;
int a = calc(1, i);
int b = calc(i + 1, j);
int c = calc(j + 1, 9);
if (n*c==a*c+b) ans++;
}
}
memcpy(path,backup,sizeof(backup));
return;
}
for (int i=1;i<=9;i++)
{
if (!vis[i])
{
vis[i]=true;
path[u]=i;
dfs(u+1);
vis[i]=false;
}
}
}
void solve()
{
cin>>n;
dfs(1);
cout<<ans;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
// cin>>t;
while (t--)
{
solve();
}
}
暴力:注释的错因是当成前缀和了,但是这不是累加各个数字,而是应该当成一个大的数
优化版
#include <bits/stdc++.h>
using namespace std;
const int N=100010;
#define int long long
int n;
int ans;
bool vis[10];
bool backup[10];
bool check(int a,int c)
{
int b=c*(n-a);
if (!a||!b||!c) return false;
memcpy(backup,vis,sizeof(vis));
while (b)
{
int x=b%10;
if(!x || backup[x]) return false;
backup[x]=true;
b/=10;
}
for (int i=1;i<=9;i++)
{
if (backup[i]==false) return false;
}
return true;
}
void dfs_c(int u, int a, int c)
{
if(u > 9) return;
if(check(a,c)) ans++;
for(int i = 1; i <= 9; i++)
{
if(!vis[i])
{
vis[i] = true;
dfs_c(u + 1, a, c * 10 + i);
vis[i] = false;
}
}
}
void dfs_a(int u, int a)
{
if(a >= n) return;
if(a) dfs_c(u, a, 0);
for(int i = 1; i <= 9; i++)
{
if(!vis[i])
{
vis[i] = true;
dfs_a(u + 1, a * 10 + i);
vis[i] = false;
}
}
}
void solve()
{
cin>>n;
dfs_a(0,0);//用了0个数,现在a的值为0
cout<<ans;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t=1;
// cin>>t;
while (t--)
{
solve();
}
}