带分数【第四届】【省赛】【A组】

题目描述

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值