dfs:选数
题目:P1036 [NOIP 2002 普及组] 选数 - 洛谷
先判断是排列还是组合(组合for循环是从1开始,排列for循环是从pos开始)。也就是说,组合不能出现数字相同的情况,例如已经有了123,又出现213,❌。排序可以。
这道选数是“组合”。
如何判断是不是质数?
- 1既不是质数,也不是合数。if (sum <= 1) return;
- 其余从2开始,一直除到sqrt(sum),if (sum % i == 0) return;

用布尔数组记录是否已经选过。这道题超时很正常,对于判断质数的优化,在以后会学。
#include <iostream>
#include <vector>
#include <cmath>const int N = 50;
typedef long long LL;using namespace std;vector<int> b;
LL a[N];
bool st[N];LL n, k;
LL ret = 0;void dfs(int pos)
{if (b.size() == k){LL sum = 0;for (auto x : b){sum += x;}if (sum <= 1) return; for (int i = 2; i <= sqrt(sum); i++){if (sum % i == 0) return;}ret++;return; } for (int i = pos; i <= n; i++){if (st[i] == true) continue;b.push_back(a[i]);st[i] = true;dfs(i);b.pop_back();st[i] = false;}
}int main()
{cin >> n >> k;for (int i = 1; i <= n ;i++) cin >> a[i];dfs(1);cout << ret;return 0;
}
