这题算是自己系统学习暴力求解法做的第一道题。总结如下: 1.在付诸于实践之前,将问题进行分析,有利于使暴力求解不单单只是暴力,还有点巧劲。 2.如一道题中有多个对象,要选取合适的对象(如范围好确定的,能乘法的不用除法等),确定其枚举范围,通过它来求解其他对象。 3.枚举目前遇到的两种思路: 1)生成—测试法:将枚举的范围扩大,再对求解出的东西进行测试看是否满足要求。适用于在枚举范围不好缩小得正正好的情况。 2)测试—生成法:就在枚举范围中处理(所谓测试,即测试是否在枚举范围中,与上面不同)。 在本题中,使用第二种很难,因为不好控制abcde和fghij是0~9的全排列。
#include <cstdio>#include <cstring>using namespace std;const int maxn=10000000000;int main(){ int abcde,fghij,n; int cnt=0; int number[10]; char sequence[20]; while(scanf("%d",&n)==1&&n){ if(cnt!=0) PRintf("/n"); bool solution=false; for(fghij=1234;fghij<=98765;fghij++){ //范围可以分析得出 memset(number,0,sizeof(number)); memset(sequence,0,strlen(sequence)); abcde=fghij*n; if(abcde+fghij>=maxn||(abcde>98765)) break; //终止枚举的条件可以分析得出 sprintf(sequence,"%d%d",abcde,fghij); for(int i=0;i<strlen(sequence);i++){ number[sequence[i]-'0']++; } bool legal=true; for(int i=1;i<10;i++) if(number[i]!=1) {legal=false;break;} if(number[0]!=1&&number[0]!=0) legal=false; if(!legal) continue; solution=true; if(number[0]==0) sprintf(sequence,"%d%s%d%d%s%d",abcde," / ",0,fghij," = ",n); else sprintf(sequence,"%d%s%d%s%d",abcde," / ",fghij," = ",n); printf("%s/n",sequence); } if(!solution) printf("There are no solutions for %d./n",n); cnt++; }}注意点: 1.sprintf的用法 2.是99999(上面的98765),不是9999
新闻热点
疑难解答