题目 1440: [蓝桥杯][2013年第四届真题]带分数

解题思路

数字1~9分别出现且只出现一次

这句话其实就是告诉我们需要用1~9的全排列,‘+’和‘/’无非就是以不同的位置插入到全排列中,然后验证分成的3个数是否满足题意。

代码实现

使用库函数版

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int cnt = 0;
    string str("123456789");// = "123456789";
    do {
        for(int i = 1; i <= 7; ++i) //加号前长度
        {
            string str_piece_one = str.substr(0, i);
            int first_num = atoi(str_piece_one.c_str());
            if(first_num >= n) break;
            for(int j = 1; j <= (9 - i - 1); ++j) //除号前长度
            {
                string str_piece_two = str.substr(i, j);
                int secone_num = atoi(str_piece_two.c_str());
                string str_piece_three = str.substr(i + j, 9 - i - j);
                int third_num = atoi(str_piece_three.c_str());
                if(secone_num % third_num == 0 && (first_num + secone_num / third_num == n))
                    ++cnt;
            }
        }
    } while(next_permutation(str.begin(), str.end()));
    cout << cnt << endl;
    return 0;
}

底层实现版

#include<iostream>
#include<cstring>
using namespace std;
char str[100], strTmp[100];
char *pstr;
int n;
int vis[100], box[100];
int size = 0, cnt = 0, ans = 0;

const char * substring(int begin, int length)
{
    strcpy(strTmp, str);
    pstr = &strTmp[begin];
    strTmp[begin + length] = '\0';
    return pstr;
}
void judge(char str[])
{
    for(int i = 1; i <= 7; ++i)
    {
        const char *str_piece_one = substring(0, i);
        int first_num = atoi(str_piece_one);
        for(int j = 1; j <= (9 - i - 1); ++j)
        {
            const char *str_piece_two = substring(i, j);
            int secone_num = atoi(str_piece_two);
            const char *str_piece_three = substring(i + j, 9 - i - j);
            int third_num = atoi(str_piece_three);
            if(secone_num % third_num == 0 && (first_num + secone_num / third_num == n))
                ++ans;
        }
    }

}
void dfs(int index)
{
    if(index == 10)
    {
        for(int i = 1; i<= cnt; ++i)
        {
            str[i - 1] = box[i] + '0';
        }
        judge(str);
        return ;
    }
    for(int i = 1; i <= 9; ++i)
    {
        if(!vis[i])
        {
            vis[i] = 1;
            box[++cnt] = i;
            dfs(index + 1);
            vis[i] = 0;
            --cnt;
        }
    }
}
int main()
{
    cin >> n;
    dfs(1);
    cout << ans << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值