枚举算法模板
穷举所有可能,逐一验证——最朴素但最可靠的算法思路
枚举
穷举
暴力
GESP3
#include <bits/stdc++.h>
using namespace std;
int main() {
// ====== 1. 百钱买百鸡 ======
// 公鸡5元 母鸡3元 小鸡1元3只,100元买100只
for (int x = 0; x <= 20; x++) // 公鸡最多20只
for (int y = 0; y <= 33; y++) { // 母鸡最多33只
int z = 100 - x - y; // 小鸡数量
if (z % 3 == 0 && 5*x + 3*y + z/3 == 100)
cout << x << " " << y << " " << z << endl;
}
// ====== 2. 两个数的最大公约数(枚举法)======
int a = 48, b = 18;
int gcd = 1;
for (int i = min(a, b); i >= 1; i--) {
if (a % i == 0 && b % i == 0) {
gcd = i;
break; // 从大到小,找到即停
}
}
cout << gcd << endl;
// ====== 3. 素数判断(枚举法)======
auto isPrime = [](int n) -> bool {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
};
cout << isPrime(17) << endl; // 1
// ====== 4. 数字全排列 ======
string s = "ABC";
do {
cout << s << endl;
} while (next_permutation(s.begin(), s.end()));
return 0;
}
📖 要点说明
- 枚举法三步:确定范围→穷举→验证
- 缩小枚举范围是关键:如百钱百鸡中公鸡最多20只
next_permutation生成全排列,需先排序
⚠️ 常见错误
- 枚举范围过大导致超时
- 忘记
break导致多输出 next_permutation前未排序导致遗漏