Files
python/TangDou/LuoGuBook/P1036_dfs_backtracking.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

53 lines
1.0 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 30;
int a[N];
int n, K;
int cnt;
int sum;
int m;
//判断一个数是不是质数
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= n / i; i++)
if (n % i == 0) return false;
return true;
}
/**
* 功能:获取可行方法数
* @param step 走在第几个箱子面前
* @return 获取可行方法数
*/
void dfs(int step) {
//脚落地
if (m == k) {
if (isPrime(sum)) cnt++;
return;//已经完成选择k个数判断和是不是质数.如果是质数,说明找到了一种合法解
}
//这句需在放在后面
if (step == n + 1) return;
//选择当前数字
sum += a[step];//回溯法
m++;
dfs(step + 1);
m--;
sum -= a[step];//加多少返多少
//放弃当前数字
dfs(step + 1);
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
dfs(1);
cout << cnt << endl;
return 0;
}