题目:
凑算式
B DEF
A + --- + ------- = 10
C GHI
(如果显示有问题,可以参见【图1. jpg】)
这个算式中A~I代表1 ~9 的数字,不同的字母代表不同的数字。
比如:
6 +8 /3 +952 /714 就是一种解法,
5 +3 /1 +972 /486 是另一种解法。
这个算式一共有多少种解法?
注意:你提交应该是个整数,不要填写任何多余的内容或说明性文字。
思路:1:暴力法,九层循环,每一层跳过重复数字。2:用全排列函数:next_permutation,再直接判断即可。
注意:GHI 和 DEF 是一个整体,一个三位数。计算其值的时候不能直接G*H*I和D*E*F, 而是(G*100+H*10+I) 和 (D*100+E*10+F)
代码:
1.暴力
#include <bits/stdc++.h>
using namespace std ;
typedef long long ll;
int main()
{
int cnt(0 );
ll sum1,sum2,sum3,sum4;
for (ll a=1 ; a<10 ; ++a) {
for (ll b=1 ;b<10 ;++b) {
if (b==a) continue ;
for (ll c=1 ;c<10 ;++c) {
if (c==b||c==a) continue ;
for (ll d=1 ;d<10 ;++d) {
if (d==c||d==b||d==a) continue ;
for (ll e=1 ;e<10 ;++e) {
if (e==d||e==c||e==b||e==a) continue ;
for (ll f=1 ;f<10 ;++f) {
if (f==a||f==b||f==c||f==d||f==e) continue ;
for (ll g=1 ;g<10 ;++g) {
if (g==a||g==b||g==c||g==d||g==e||g==f) continue ;
for (ll h=1 ;h<10 ;++h) {
if (h==a||h==b||h==c||h==d||h==e||h==f||h==g) continue ;
for (ll i=1 ;i<10 ;++i) {
if (i==a||i==b||i==c||i==d||i==e||i==f||i==g||i==h) continue ;
sum1 = a*c*(g*100 +h*10 +i);
sum2 = b*(g*100 +h*10 +i);
sum3 = c*(d*100 +e*10 +f);
sum4 = 10 *c*(g*100 +h*10 +i);
if (sum1+sum2+sum3==sum4) {
cout << a << ends << b << ends << c << ends;
cout << d << ends << e << ends << f << ends;
cout << g << ends << h << ends << i << ends;
cout << endl;
cnt += 1 ;
}
}
}
}
}
}
}
}
}
}
cout << cnt << endl;
return 0 ;
}
2.用全排列函数:next_permutation
#include <bits/stdc++.h>
using namespace std ;
typedef long long ll;
int main()
{
ll sum1, sum2, sum3, sum4;
int a[10 ], cnt(0 );
for (int i=1 ;i<10 ;++i) a[i] = i;
do {
sum1 = a[1 ]*a[3 ]*(a[7 ]*100 +a[8 ]*10 +a[9 ]);
sum2 = a[2 ]*(a[7 ]*100 +a[8 ]*10 +a[9 ]);
sum3 = a[3 ]*(a[4 ]*100 +a[5 ]*10 +a[6 ]);
sum4 = 10 *a[3 ]*(a[7 ]*100 +a[8 ]*10 +a[9 ]);
if (sum1+sum2+sum3==sum4) cnt += 1 ;
}while (next_permutation(a+1 ,a+10 ));
cout << cnt << endl;
return 0 ;
}