You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 30;
int a[N];
int n, k;
int cnt;
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;
}
/**
* 功能:遍历每个卡片(数字),携带已经选择了几个的m参数
* @param step 第几个卡片
* @param sum 已经选择的数字总和
* @param m 已经选择了几个数字
* @return 可行方法数
*/
void dfs(int step, int sum, int m) {
//已经完成选择k个数判断总和是不是质数.如果是质数,说明找到了一种合法解
if (m == k && isPrime(sum)) {
cnt++;
return;
}
//这句需在放在后面,这是因为如果是第n个摆放完的数字满足上面的判断条件也是可以的
if (step == n + 1) return;
//选择当前数字,总和增大a[step],同时个数增加了1
dfs(step + 1, sum + a[step], m + 1);
//放弃当前数字,总和不变,个数也不变
dfs(step + 1, sum, m);
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
dfs(1, 0, 0);
cout << cnt << endl;
return 0;
}