凑算式
B DEF
A + --- + ------- = 10
C GHI
(如果显示有问题,可以参见【图1.jpg】)
这个算式中A~I代表1~9的数字,不同的字母代表不同的数字。
比如:
6+8/3+952/714 就是一种解法,
5+3/1+972/486 是另一种解法。
这个算式一共有多少种解法?
注意:你提交应该是个整数,不要填写任何多余的内容或说明性文字。
本题可以用dfs做 一个数一个数的搜索 也可以写9个for循环 直到发现了一种最简单的方法:
next_permutation
可以用各种类型的数组,包括string类,从数组初始值 走到下一个字典序
两个参数是想要遍历字典序的起始位置和结束位置。
string类需要传进的是迭代器
code:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
double a[9]={1,2,3,4,5,6,7,8,9};
int c;
int main()
{while(next_permutation(a,a+9)){if(a[0]+a[1]/a[2]+(a[3]*100+a[4]*10+a[5])/(a[6]*100+a[7]*10+a[8])==10.0) c++;} cout<<c<<endl; return 0;
}
dfs:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int a[10],c;
bool book[10];
bool check()
{double p,c;int b,m;p=a[2]*1.0/a[3];b=a[4]*100+a[5]*10+a[6];m=a[7]*100+a[8]*10+a[9];c=b*1.0/m;if(a[1]+p+c==10)return 1;return 0;
}
void dfs(int n)
{if(n>9&&check()){c++;}else{for(int i=1;i<10;i++){if(!book[i]){book[i]=1;a[n]=i;dfs(n+1);book[i]=0;}}}
}
int main()
{dfs(1); cout<<c<<endl;return 0;
}