第二章-暴力求解-计算机考研机试笔记
2.1 枚举
枚举是指对每个可能的解逐一进行判断,直到找到符合题目要求的答案。
采取枚举策略前,一定要分析枚举量。枚举量过大时,需要选择其他办法解决。即使题目适合枚举法,也要进行分析以减少无用的枚举。
枚举类题目的特点:数据量较小时,可以逐个判断数据是否符合题目的要求。
例题2.1:abc
例题2.2:反序数
经典函数需牢记:
1 2 3 4 5 6 7 8 9
| int Reverse(int x){ int revx = 0; while (x!=0){ revx*=10; revx+=x%10; x/=10; } return revx; }
|
例题2.3:对称平方数1(反序数的应用)
习题2.1:与7无关的数
我的答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> #include <cstdio>
using namespace std;
int main(){ int n; while(scanf("%d",&n) != EOF){ int sum=0; for(int i=1;i<=n;i++){ if(i%7==0 || i%10==7 || (i/10)%10==7) continue; else sum+=i*i; } printf("%d\n",sum); } return 0; }
|
习题2.2:百鸡问题
我的答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream>
using namespace std;
int main(){ int n; while(scanf("%d",&n) != EOF){ for(int i=0;i<=100;i++){ for(int j=0;j<=100-i;j++){ int k=100-i-j; if(15*i+9*j+k<=3*n) printf("x=%d,y=%d,z=%d\n",i,j,k); } } } return 0; }
|
习题2.3:Old Bill
我的答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| #include <iostream>
using namespace std;
int main(){ int n,x,y,z; int total; while(scanf("%d",&n)!=EOF && scanf("%d %d %d",&x,&y,&z)!=EOF){ int temp,tempi,tempj=0; for(int i=9;i>0;i--){ for(int j=9;j>=0;j--){ total=10000*i+1000*x+100*y+10*z+j; if(total%n==0) if(total/n>temp){ temp=total/n; tempi=i; tempj=j; } else continue; } } if(temp==0) printf("0\n"); else printf("%d %d %d\n",tempi,tempj,temp); } return 0; }
|