题目描述
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
B DEF
A + --- + ------- = 10
C GHI
这个算式中 A ~ I 代表 1 ~ 9 的数字,不同的字母代表不同的数字。
比如: 6+8/3+952/7146+8/3+952/714 就是一种解法, 5+3/1+972/4865+3/1+972/486 是另一种解法。
这个算式一共有多少种解法?
思路:学个next-permutation像hello world 一样简单
这道题 很多暴力枚举 和递归的解法 都很麻烦 直接全排列几行就搞定(这个函数太强了)
1.暴力枚举 (要写n重循环,反正填空题,倒也不难,就是费手)
#include<iostream>
using namespace std;
int main()
{
int s=0;
for(int a=1;a<10;a++)
for(int b=1;b<10;b++){
if(a!=b){
for(int c=1;c<10;c++){
if(c!=a&&c!=b){
for(int d=1;d<10;d++){
if(d!=a&&d!=b&&d!=c){
for(int e=1;e<10;e++){
if(e!=a&&e!=b&&e!=c&&e!=d){
for(int f=1;f<10;f++){
if(f!=a&&f!=b&&f!=c&&f!=d&&f!=e){
for(int g=1;g<10;g++){
if(g!=a&&g!=b&&g!=c&&g!=d&&g!=e&&g!=f){
for(int h=1;h<10;h++){
if(h!=a&&h!=b&&h!=c&&h!=d&&h!=e&&h!=f&&h!=g){
for(int i=1;i<10;i++){
if(i!=a&&i!=b&&i!=c&&i!=d&&i!=e&&i!=f&&i!=g&&i!=h){
int m=g*100+h*10+i;
int n=d*100+e*10+f;
if((b*n+c*m)/(c*n)==10-a&&(b*n+c*m)%(c*n)==0)
s++;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
printf("%d",s);
return 0;
}
2,递归回溯
#include<iostream>
using namespace std;
int a[]={1,2,3,4,5,6,7,8,9};
int sum=0;
void f(int x)
{
if(x==9)
int p=a[3]*100+a[4]*10+a[5];
int q=a[6]*100+a[7]*10+a[8];
if((a[1]*q+a[2]*p)%(a[2]*q)==0&&a[0]+(a[1]*q+a[2]*p)/(a[2]*q)==10)
sum++;
return;
}
for(int i=x;i<9;i++)
{
int t=a[i];a[i]=a[x];a[x]=t;
f(x+1);//递归
t=a[i];a[i]=a[x];a[x]=t;//回溯
}
}
int main()
{
f(0);
cout<<sum;
return 0;
}
3,重点来了 直接上仙术 next—permutation 几行搞定
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
double a[]={1,2,3,4,5,6,7,8,9};
long long c=0;
do{
if(a[0]+a[1]/a[2]+(a[3]*100+a[4]*10+a[5])/(a[6]*100+a[7]*10+a[8])==10){
c++;
}
}while(next_permutation(a,a+9));
cout<<c;
return 0;
}
这个函数真的很强大,可以求出数组的所有排列组合,这道题注意用double型就可以了,因为整形会自动取整嘛,会丢结果。