一、问题
二、暴力枚举
1、思路
可以先全排列出所有的情况,然后根据每一种情况再使用隔板法。
时间复杂度:
9
!
∗
9
∗
C
8
2
=
9
!
∗
9
∗
4
∗
7
=
91445760
9!*9*C_8^2=9!*9*4*7= 9144 5760
9!∗9∗C82=9!∗9∗4∗7=91445760,大概是108的时间复杂度,恰好能在1秒之内算完。
2、代码
/*
DFS+隔板法:
9!*9*4*7=9144 5760=9*10^8=1^9
*/
#include<iostream>
using namespace std;
bool st[10];
int a[10];
int n;
int ans;
int qmi(int a,int b)
{
int res=1;
while(b)
{
if(b&1)res*=a;
a*=a;
b>>=1;
}
return res;
}
int cal(int x,int y)
{
int res=0;
for(int i=0;i<y-x+1;i++)
{
res+=a[x+i]*qmi(10,i);
}
return res;
}
void dfs(int u)
{
if(u>=9)
{
for(int i=1;i<9;i++)
{
for(int j=i;j<8;j++)
{
int x1=cal(0,i-1);
int x2=cal(i,j);
int x3=cal(j+1,8);
if(x2%x3==0&&n==(x1+x2/x3))
{
ans++;
}
}
}
}
for(int i=1;i<=9;i++)
{
if(!st[i])
{
st[i]=true;
a[u]=i;
dfs(u+1);
st[i]=false;
}
}
}
int main()
{
cin>>n;
dfs(0);
cout<<ans<<endl;
return 0;
}
三、优化
1、思路
我们发现,我们去枚举了三个变量的所有可能,但是我们可以只枚举其中的两个,然后利用这两个数字算出第三个,再看第三个值的位数组成是否和前面的两个数的某位重复。
2、代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
bool st[N], backup[N];
int ans;
bool check(int a, int c)
{
long long b = n * (long long)c - a * c;
if (!a || !b || !c) 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 u, int a, int c)
{
if (u > 9) return;
if (check(a, c)) ans ++ ;
for (int i = 1; i <= 9; i ++ )
if (!st[i])
{
st[i] = true;
dfs_c(u + 1, a, c * 10 + i);
st[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 (!st[i])
{
st[i] = true;
dfs_a(u + 1, a * 10 + i);
st[i] = false;
}
}
int main()
{
cin >> n;
dfs_a(0, 0);
cout << ans << endl;
return 0;
}