第三届蓝桥杯省赛---马虎的算式

小明是个急性子,上小学的时候经常把老师写在黑板上的题目抄错了。
有一次,老师出的题目是:36 x 495 = ?
他却给抄成了:396 x 45 = ?
但结果却很戏剧性,他的答案竟然是对的!!
假设 a b c d e 代表1~9不同的5个数字(注意是各不相同的数字,且不含0)
能满足形如: ab * cde = adb * ce 这样的算式一共有多少种呢?
请你利用计算机的优势寻找所有的可能,并回答不同算式的种类数。
满足乘法交换律的算式计为不同的种类,所以答案肯定是个偶数。
因为 36 * 495 = 396 * 45 = 17820
类似这样的巧合情况可能还有很多,比如:27 * 594 = 297 * 54

分析: 

思路一:暴力枚举各个位置上的值

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 int main(){
 5     int a,b,c,d,e;
 6     int ans=0;
 7     for( a=1; a<=9; a++ ){
 8         for( b=1; b<=9; b++ ){
 9             for( c=1; c<=9; c++ ){
10                 for( d=1; d<=9; d++ ){
11                     for( e=1; e<=9; e++ ){
12                         if((a*10+b)*(c*100+d*10+e)==(a*100+d*10+b)*(c*10+e)&&a!=b&&a!=c&&a!=d&&a!=e&&
13                             b!=c&&b!=d&&b!=e&&c!=d&&c!=e&&d!=e){
14                             ans++;
15                         }
16                     }
17                 }
18             }
19         }
20     }
21     printf("%d
",ans);
22     return 0;
23 }

思路二:dfs全排列,筛选条件,运用visited函数有效的避免重复数字

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 #define ll long long 
 8 int visited[10];/*数组值为1代表选用这个数,为0代表不选用*/
 9 ll ans = 0;
10 
11 bool test(int a[] ){/*检查是否符合条件*/
12     if((a[1]*10+a[2])*(a[3]*100+a[4]*10+a[5])==(a[1]*100+a[4]*10+a[2])*(a[3]*10+a[5])){
13         return true;
14     }
15     else{
16         return false;
17     }
18 }
19 
20 void dfs(int k,int a[]){
21     if(k==6){
22         if(test(a)){
23             ans++;
24         }
25         return ;
26     }
27     for( int i=1; i<=9; i++ ){
28         if(!visited[i]){
29             a[k]=i;
30             visited[i]=1;
31             dfs(k+1,a);
32             /*不选用这个数,恢复默认值*/
33             visited[i]=0;
34             a[k]=0;
35         }
36     }
37 }
38 
39 int main(){
40     int a[10];
41     dfs(1,a);
42     cout<<ans<<endl;
43     return 0;
44 }
有些目标看似很遥远,但只要付出足够多的努力,这一切总有可能实现!
原文地址:https://www.cnblogs.com/Bravewtz/p/10427366.html