题目描述
100 可以表示为带分数的形式:100 = 3 + 69258 / 714
还可以表示为:100 = 82 + 3546 / 197
注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。
类似这样的带分数,100 有 11 种表示法。
题目要求
从标准输入读入一个正整数N (N<1000*1000)
程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。
注意:不要求输出每个表示,只统计有多少表示法!
输入输出
用户输入:
100
程序输出:
11
再例如:
用户输入:
105
程序输出:
6
资源约定
峰值内存消耗 < 64M
CPU消耗 < 3000ms
思路
思路很简单,就是首先生成1~9的全排列,然后对这个全排列进行暴力枚举,然后再去判断是否能够凑成给定的目标值,生成全排列可以使用DFS
也可以使用next_permutation
代码(DFS)
#include <iostream>
using namespace std;
const int N = 10;
int n;
int num[N];
bool st[N];
int res;
int cal(int l, int r)
{
int c = 0;
for ( int i = l; i <= r; i ++ )
c = c * 10 + num[i];
return c;
}
void dfs(int u)
{
if ( u == 9 )
{
for ( int i = 0; i < 7; i ++ )
{
for ( int j = i + 1; j < 8; j ++ )
{
int a = cal(0, i);
int b = cal(i + 1, j);
int c = cal(j + 1, 8);
if ( b % c ) continue;
if ( a + b / c == n ) res ++;
}
}
}
for ( int i = 0; i < 9; i ++ )
{
if ( !st[i] )
{
st[i] = true;
num[u] = i + 1;
dfs(u + 1);
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(0);
cout << res << endl;
return 0;
}
代码(next_permutation)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 10;
int n;
int num[N];
bool st[N];
int res;
int cal(int l, int r)
{
int c = 0;
for ( int i = l; i <= r; i ++ )
c = c * 10 + num[i];
return c;
}
int main()
{
cin >> n;
for ( int i = 0; i < 9; i ++ ) num[i] = i + 1;
do {
for ( int i = 0; i < 7; i ++ )
{
for ( int j = i + 1; j < 8; j ++ )
{
int a = cal(0, i);
int b = cal(i + 1, j);
int c = cal(j + 1, 8);
if ( b % c ) continue;
if ( a + b / c == n ) res ++;
}
}
} while( next_permutation(num, num + 9) );
cout << res << endl;
return 0;
}