暴力求解之枚举
枚举
枚举是指对每个可能的解进行逐一判断,直到找到符合题目要求的答案。枚举类的题目本身并不复杂,但在采取枚举策略之前,一定要好好的分析题目的枚举量,枚举量过大的时候,需要选择其他的解决方法。即使问题适合枚举,也要进行分析,以便通过减少部分无效的枚举来使程序更加的简洁和高效。
例题
一、abc(清华大学复试上机题)
题目
三重循环解法
| #include <iostream> |
| #include<cstdio> |
| using namespace std; |
| |
| int main() { |
| for (int i = 1; i <= 9; i++) { |
| for (int j = 1; j <= 9; j++) { |
| for (int k = 0; k <= 9; k++) { |
| if (100*i+110*j+12*k == 532) { |
| printf("%d %d %d\n",i,j,k); |
| } |
| } |
| } |
| } |
| } |

二、反序数(清华大学复试上机题)
题目
一重循环解法
| #include <iostream> |
| using namespace std; |
| int R(int x){ |
| int revx=0; |
| while(x!=0){ |
| revx *= 10; |
| revx += x%10; |
| x/=10; |
| } |
| return revx; |
| } |
| int main() { |
| for(int i=1000;i<=9999;i++){ |
| if(i*9==R(i)){ |
| printf("%i\n",i); |
| } |
| } |
| } |
| |
| |

四重循环解法
| #include <iostream> |
| using namespace std; |
| |
| int main() { |
| int a, b, c, d; |
| for (int a = 1; a <= 9; a++) { |
| for (int b = 0; b <= 9; b++) { |
| for (int c = 0; c <= 9; c++) { |
| for (int d = 0; d <= 9; d++) { |
| |
| int num1 = 1000 * a + 100 * b + 10 * c + d; |
| int num2 = 1000 * d + 100 * c + 10 * b + a; |
| if (9*num1 == num2) { |
| printf("%d\n", num1); |
| } |
| |
| |
| } |
| } |
| } |
| } |
| } |
| |

三、对称平方数1(清华大学复试上机题)
题目
解法
| #include <iostream> |
| #include <cmath> |
| using namespace std; |
| int R(int x) { |
| int revx = 0; |
| while (x != 0) { |
| revx *= 10; |
| revx += x % 10; |
| x /= 10; |
| } |
| return revx; |
| } |
| int main() { |
| for (int i = 0; i <= 256; i++) { |
| if (pow(i,2) == R(pow(i,2))) { |
| printf("%d\n", i); |
| } |
| } |
| } |
| |

补充知识(cmath库)
| #include <cmath> |
| pow(a,b) |
| sqrt(x) |
| abs(n) |
| fabs(m) |
本文作者:Franletus
本文链接:https://www.cnblogs.com/yidianxingyuan/p/18116282
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步