第四届蓝桥杯——带分数

【问题描述】
100 可以表示为带分数的形式:100 = 3 + 69258 / 714
还可以表示为:100 = 82 + 3546 / 197
注意特征:带分数中,数字 1∼9 分别出现且只出现一次(不包含 0)。

类似这样的带分数,100 有 11 种表示法。

【输入格式】
一个正整数。

【输出格式】
输出输入数字用数码 1∼9 不重复不遗漏地组成带分数表示的全部种数。

【数据范围】
1 ≤ N < 10^6

【输入样例1】
100

【输出样例1】
11

【输入样例2】
105

【输出样例2】
6


解题思路: 用DFS求出 1~9 的全排列,然后分别取位数,分成 a,b,c 三个数,最后判断是否符合要求即可

题解1
DFS:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 10;

int n, ans;

// a 数组用来存数字, st 数组判断数字是否被用过
int a[N], st[N];

int get(int start, int end)
{
    int num = 0;
    for (int i = start; i <= end; i ++) num = num*10 + a[i];
    
    return num;
}

void dfs(int step)
{
    if(step == 9)
    {
        for (int i = 0; i < 6; i ++)        // a 小于1000000,所以取六位即可
           for (int j = i + 1; j < 8; j ++) // 至少留一位给 c,所以 b 最多取七位
           {
               int a = get(0, i);
               int b = get(i + 1, j);
               int c = get(j + 1, 8);
               
               if(a + 1.0*b / c == n) ans ++;
           }
           return;
    }
    
    for (int i = 1; i <= 9; i ++)
    {
        if(!st[i])
        {
            a[step] = i;
            st[i] = true;
            
            dfs(step + 1);
            
            // 回溯
            a[step] = 0;
            st[i] = false;
        }
    }
}
int main()
{
    cin >> n;
    dfs(0);
    cout << ans << endl;
    return 0;
}

题解2
全排列:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

int n, ans;
int a[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

int get(int l, int r)
{
    int res = 0;
    for (int i = l; i <= r; i ++) res = res * 10 + a[i];
    
    return res;
}

int main()
{
    cin >> n;
    
    do
    {
        for (int i = 0; i < 6; i ++)
            for (int j = i + 1; j < 8; j ++)
            {
                int a = get(0, i);
                int b = get(i + 1, j);
                int c = get(j + 1, 8);
                
                if (a + 1.0*b / c == n) ans ++;
            }
            
    }while(next_permutation(a, a + 9));
    
    cout << ans << endl;
    
    return 0;
}



发布了63 篇原创文章 · 获赞 5 · 访问量 828

猜你喜欢

转载自blog.csdn.net/weixin_46239370/article/details/105340076