引言
有时候题目需要换一种思维,才能想到解题方法。
尤其是蓝桥杯这种比赛,总是跟经典例题相关的,要尽量把思路往上面靠。
题面
思路
- 逆向思考,不去凑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(大概在中间部位)