带分数——蓝桥杯

带分数——蓝桥杯

今天刷题刷到这题,其实题本身思路挺简单,就是一个库函数引起了我的兴趣。

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
100 可以表示为带分数的形式:100 = 3 + 69258 / 714。
还可以表示为:100 = 82 + 3546 / 197。
注意特征:带分数中,数字1~9分别出现且只出现一次(不包含0)。
类似这样的带分数,100 有 11 种表示法。
输入格式
从标准输入读入一个正整数N (N<1000*1000)
输出格式
程序输出该数字用数码1~9不重复不遗漏地组成带分数表示的全部种数。

注意:不要求输出每个表示,只统计有多少表示法!

样例输入1
100
样例输出1
11
样例输入2
105
样例输出2
6

解题思路就是从这里下手:
将1-9进行全排列,然后从中间按照某种顺序截取三段,以这三段分别作为a、b、c,接着带入那个公式,并将得到的结果与输入的数比较(a+1.0*b/c==m),最后利用数组的随机访问特性直接输出结果即可(即假设给出下面某种排列:123|4567|89,则你可以在这串数中任意插入两根棍子,将其分成三部分)。
其中全排列就用到了next_permutation()函数,它包含在algorithm库函数中。
1.字符串全排列:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	string s;
	cin>>s;
	cout<<s<<" ";
	while(next_permutation(s.begin(),s.end())){
		cout<<s<<" ";
	}
	return 0;
}

结果:
在这里插入图片描述

2.int全排列:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int a[100],n;
	cin>>n;
	for(int i=0;i<n;++i){
		scanf("%d",&a[i]);
	}
	//cout<<a[0];
	while(next_permutation(a,a+n)){
		for(int i=0;i<n;++i){
			cout<<a[i]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

结果:
在这里插入图片描述
附答案:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    int m = 0;
    cin >> m;
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int cnt = 0;
    long long n1, n2, n3;
    do{
        for (int i = 1; i <= 7;i++){
            for (int j = 1; j <= 8 - i;j++){
                n1 = n2 = n3 = 0;
                int x = 0, q = 0;
                for (x = 0; x < i;x++){
                    n1 = n1 * 10 + a[q];
                    q++;
                }
                for (x = 0; x < j;x++){
                    n2 = n2 * 10 + a[q];
                    q++;
                }
                for (x = 0; x <= 8-i-j;x++){
                    n3 = n3 * 10 + a[q];
                    q++;
                }
                if((n1+1.0*n2/n3)==m)
                cnt++;
            }}
            
    } while (next_permutation(a, a+9));
    cout << cnt;
    return 0;
}

next_permutation函数参考:
https://blog.csdn.net/mm114820/article/details/88059987

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值