一个穷举题

题目:

ab-cd=ef=g*hi,字母表示1~9的数字,不能重复。


出于效率,用C编写

 

思路如下,ab从大到小遍历,这样可以早接近答案,其余的从小到大遍历;

ab、cd确定之后,直接算出ef并且判重,在ef没有重复且大于0时,遍历g,并直接计算hi,判断是否能整除及是否重复。

为了编写方便,判重利用的是状态数组,没有采用位操作。

整体算法复杂度o(n^5),由于数据规模很小,复杂度可以接受。

 

 1#include <stdio.h>
 2#include <stdlib.h>
 3int main(){
 4    short a,b,c,d,e,f,g,h,i,temp,t,t0;
 5    short status[10]={0,0,0,0,0,0,0,0,0};
 6    for (a=9;a>0;a--){
 7        if(status[a]) continue;
 8        status[a]=1;
 9        for(b=9;b>0;b--){
10            if (status[b])    continue;
11            status[b]=1;
12            for(c=1;c<10;c++){
13                if (status[c])    continue;
14                status[c]=1;
15                for(d=1;d<10;d++){
16                    if (status[d])    continue;
17                    status[d]=1;
18                    temp=a*10+b-(c*10+d);
19                    e=temp-(temp/10)*10;
20                    f=temp/10;
21                    if (status[e]||status[f]){
22                        status[d]=0;
23                        continue;
24                    }

25                    status[e]=1;
26                    status[f]=1;
27                    for(g=1;g<10;g++){
28                        if (status[g])    continue;
29                        status[g]=1;
30                        t=temp%g;
31                        if (!t){
32                            t0=temp/g;
33                            h=t0-(t0/10)*10;
34                            i=t0/10;
35                            if (status[h]||status[i]){
36                                status[g]=0;
37                                continue;
38                            }

39                            printf("%d%d-%d%d=%d%d=%d*%d%d",a,b,c,d,e,f,g,h,i);
40                            exit(0);
41                        }

42                    }

43                    status[d]=0;
44                    status[e]=0;
45                    status[f]=0;
46                }

47                status[c]=0;
48            }

49            status[b]=0;
50        }

51        status[a]=0;
52    }

53    return 0;
54}

答案是93-25=68=4*1
posted @ 2009-10-26 00:01  Justin Wong  阅读(211)  评论(0)    收藏  举报