/* ID:tianlin2 PROG:crypt1 LANG:C++ */ #include <iostream> #include <fstream> using namespace std; bool ina(int a[],int cou,int dit) { //注意0的情况 if(dit==0) return false; while(dit!=0) { int c=dit%10; int i; for(i=0;i!=cou;++i) { if(c==a[i]) break; } if(i==cou) return false; dit=dit/10; } return true; } int max(int a[],int cou) { int b=0; for(int i=0;i!=cou;++i) { if(a[i]>b) b=a[i]; } return b; } int main() { ofstream fout("crypt1.out"); ifstream fin("crypt1.in"); int cou,a[10]; //用来计数的 int num=0,h=1; fin>>cou; for(int i=0;i!=cou;++i) fin>>a[i]; int m=max(a,cou); //算界限 int up=m*100+m*10+m; int down=m*10+m; for(int i=111;i<=up;++i) { if(!ina(a,cou,i)) continue; for(int j=11;j<=down;++j) { if(!ina(a,cou,j)) continue; //模拟竖式,以竖式的方式判断,很麻烦 int b=(j%10)*i; int c=(j/10)*i; if(!ina(a,cou,b)||!ina(a,cou,c)||b>up||c>up) continue; //看了官方答案才知道,原来最后一个数可以这样 /* if(!ina(a,cou,i*j))||i*j>9999) continue; ++num; */ int markb=0; int markc=0; int store=0; if(!ina(a,cou,b%10)) continue; markb=(b/10)%10; markc=c%10; if(!ina(a,cou,(markb+markc)%10)) continue; store=(markb+markc)/10; markb=b/100; markc=(c/10)%10; if(!ina(a,cou,(markb+markc+store)%10)) continue; store=(markb+markc)/10; markc=c/100; if((markc+store)>9) continue; if(!ina(a,cou,markc+store)) continue; ++num; } } fout<<num<<endl; //system("pause"); return 0; } 看了官方答案才知道自己做得很笨拙!,见注释 期间还因为函数里0的情况卡住了! 官方答案: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> int isgooddigit[10]; /* isgooddigit[d] is set if d is an acceptable digit */ /* check that every decimal digit in "n" is a good digit, and that it has the right number "d" of digits. */ int isgood(int n, int d) { if(n == 0) return 0; while(n) { if(!isgooddigit[n%10]) return 0; n /= 10; d--; } if( d == 0 ) return 1; else return 0; } /* check that every product line in n * m is an okay number */ int isgoodprod(int n, int m) { if(!isgood(n,3) || !isgood(m,2) || !isgood(n*m,4)) return 0; while(m) { if(!isgood(n*(m%10),3)) return 0; m /= 10; } return 1; } void main(void) { int i, j, n, nfound; FILE *fin, *fout; fin = fopen("crypt1.in", "r"); fout = fopen("crypt1.out", "w"); assert(fin != NULL && fout != NULL); for(i=0; i<10; i++) { isgooddigit[i] = 0; } fscanf(fin, "%d", &n); for(i=0; i<n; i++) { fscanf(fin, "%d", &j); isgooddigit[j] = 1; } nfound = 0; for(i=100; i<1000; i++) for(j=10; j<100; j++) if(isgoodprod(i, j)) nfound++; fprintf(fout, "%d/n", nfound); exit(0); }