100 可以表示为带分数的形式:100=3+69258714
还可以表示为:100=82+3546197
注意特征:带分数中,数字 1∼9 分别出现且只出现一次(不包含 0)。
类似这样的带分数,100 有 11 种表示法。
输入格式
一个正整数。
输出格式
输出输入数字用数码 1∼9 不重复不遗漏地组成带分数表示的全部种数。
数据范围
1≤N<106
输入样例1:
100
输出样例1:
11
输入样例2:
105
输出样例2:
6
思路:
-暴力枚举出9个数全排列。用一个数组保存全排列的结果;
-从全排列的结果中用两重循环暴力分解出三段,每段代表一个数;
-判断枚举出来的三个数是否满足条件,满足则计数;
-n = a + b/c <----> cn = ac + b <----> b = cn - ca
解法一:
#include <bits/stdc++.h>
using namespace std;
const int N =10;
int n;
int num[N];//保存全排列的结果
int ans;//计数
bool st[N];//判断这个数是否被用过
int calc(int l , int r)//计算num数组中一段的数是多少
{
int res = 0 ;
for(int i = l ; i <= r ; i++)
res = res*10 + num[i]; //表示在个位加上一个数:如想在12后面加个3变成123,则12*10+3
return res;
}
void dfs(int u) //u表示当前已经标记使用了u个数字
{
if(u == 9)
{ //用两重循环将全排列的数,分成三段
for(int i = 0 ; i < 7 ;i++)
for(int j = i + 1 ; j < 8 ;j++)
{
int a = calc( 0 , i);
int b = calc( i + 1 , j);
int c = calc(j + 1 , 8);
if(a * c + b == c * n) ans++;
}
return;
}
//搜索
for(int i = 1 ;i <= 9 ;i++)
{
if(!st[i])
{
num[u] = i ;
st[i] =true;//标记使用过
dfs(u + 1);
st[i] =false;//恢复现场
}
}
}
int main()
{
cin>>n;
dfs(0);
cout<<ans<<endl;
return 0;
}
解法二:使用STL全排列函数next_permutation()
#include <bits/stdc++.h>
using namespace std;
const int N =10;
int n;
int num[N];//保存全排列的结果
int ans;//计数
int calc(int l , int r)//计算num数组中一段的数是多少
{
int res = 0 ;
for(int i = l ; i <= r ; i++)
res = res*10 + num[i]; //表示在个位加上一个数:如想在12后面加个3变成123,则12*10+3
return res;
}
int main()
{
cin>>n;
for(int i = 1 ;i <= 9 ;i++)
num[i-1] = i;
do{
for(int i = 0 ;i < 7 ;i++)
for(int j = i + 1 ; j < 8 ;j++)
{
int a = calc( 0 , i);
int b = calc( i + 1 , j);
int c = calc( j + 1 , 8);
if(a*c + b == n*c) ans++;
}
}while(next_permutation(num , num +9));
cout<<ans<<endl;
return 0;
}
解法三:(优化版)
思路:
*先枚举a
*对于每个a的叶子结点,再枚举c,拓展成一颗搜索树
*a,c确定了,那么b也就确定了,根据条件,判断a,b,c是否成立
#include <bits/stdc++.h>
using namespace std;
const int N = 20;
int n,ans;
bool st[N],tmp[N];
bool check(int a ,int c)
{
long long b = (long long)c*n -a*c;//因为 n*c 可能会溢出int从而变成负数, 所以使用long long
if( !a || !b || !c) return false;
memcpy(tmp , st , sizeof st);//将名为st,大小为st的数组复制给tmp数组
while(b)
{
int x = b % 10; //取出b的个位数
b /=10; //去掉个位数
if(!x||tmp[x]) return false; //如果x为0或者x出现了a,b中的数(题目要求每个数字仅出现一个),则不满足条件
tmp[x] =true;//把每个数都定为true
}
for(int i = 1 ;i<=9 ;i++)
{
if(!tmp[i]) return false; // 1`9有未出现在tmp数组的数,则不满足条件
}
return true;
}
void dfs_c(int u , int a , int c)
{
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;
}