*2013蓝桥杯 C/C++ B组9 带分数 [提高]

引言

有时候题目需要换一种思维,才能想到解题方法。
尤其是蓝桥杯这种比赛,总是跟经典例题相关的,要尽量把思路往上面靠。

题面

在这里插入图片描述

思路
  • 逆向思考,不去凑1~9,而是1-9做全排列
  • 全排列C++有内置库函数next_permutation()
  • 在每个全排列中插入+和/ 切分为三部分:整数+分子+分母
代码(tle)
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
int aa,bb,cc;
int main()
{
	string s="123456789";
	string a="+";
	string b="/";
	int n,t,ln=0;
	cin >> n;
	t = n;
	while(t) {
		t/=10;
		ln ++;
	}
	string :: iterator it = s.begin();
	int num=0;
	do{
		string tmp = s;
		for(int i=1;i<=ln;i++) {
			tmp.insert(tmp.begin()+i,'+');
			for(int j=9;j>=i+2;j--) {
				tmp.insert(tmp.begin()+j,'/');
				sscanf(tmp.c_str(),"%d+%d/%d",&aa,&bb,&cc);
				if(bb%cc==0 && aa+bb/cc==n) {
					num++;
				}
				tmp.erase(tmp.begin()+j,tmp.begin()+j+1);
			}
			tmp.erase(tmp.begin()+i,tmp.begin()+i+1);
		}
	}while(next_permutation(s.begin(),s.end()));
	cout << num;
	
	return 0;
}
AC代码
#include<iostream>
#include<algorithm>
#include<string>
#include<cmath>

using namespace std;

int n,tmp,cnt;
int a,b,c;
int num[9]={1,2,3,4,5,6,7,8,9};
int toint(int num[],int beg,int end) {
	int res = 0;
	for(int i=beg;i<=end;i++) {
		res += num[i]*pow(10,end-i);
	}
	return res;
}

int main()
{
//	string s = "123456789";
	
	scanf("%d",&n);
	tmp = n;
	int k = 0;
	while(tmp) {
		tmp /= 10;
		k ++;
	}
	do{
		for(int i=0;i<k;i++) {
			a = toint(num,0,i);
			if(a >= n) break;
			for(int j=(7-i+1)/2+i;j<=7;j++) {
				b = toint(num,i+1,j);
				c = toint(num,j+1,8);
				if(a+b/c>n) break;
				if(b%c==0 && a+b/c==n) cnt++;
			}
		}
		
		
	}while(next_permutation(num,num+9));
	printf("%d",cnt);
	
	return 0;
}

带分数
注意:

  • string字符串处理非常非常慢,一般能不用就不用,字符串用char[],表示数字时不妨用int[]数组表示。
  • next_permutation()名字忘了怎么办?
    流程:进入algorithm
    进入stl.aglo
    ctrl+f查找“next_per"或者一个个查找"per"或者查看2909(大概在中间部位)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值