选数 2002年NOIP全国联赛普及组

题目描述 Description

已知 n 个整数 x1,x2,…,xn,以及一个整数 k(k<n)。从 n 个整数中任选 k 个整数相加,可分别得到一系列的和。例如当 n=4,k=3,4 个整数分别为 3,7,12,19 时,可得全部的组合与它们的和为:
3+7+12=22  3+7+19=29  7+12+19=38  3+12+19=34。
现在,要求你计算出和为素数共有多少种。
例如上例,只有一种的和为素数:3+7+19=29)。

输入描述 Input Description

 键盘输入,格式为:
n , k (1<=n<=20,k<n)
x1,x2,…,xn (1<=xi<=5000000)

输出描述 Output Description

屏幕输出,格式为:
一个整数(满足条件的种数)。

样例输入 Sample Input

4 3
3 7 12 19

样例输出 Sample Output

1

数据范围及提示 Data Size & Hint

(1<=n<=20,k<n)
(1<=xi<=5000000)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int num[2333], k, n, ans = 0;
bool ispri(int s)
{
	for (int i = 2; i <= sqrt(s); i++)
		if (s % i == 0)
			return 0;
	return 1;
}
void dfs(int t, int s, int l)
{
	if (t == k)
	{
		if (ispri(s))
			ans++;
	}
	else
		for (int i = l; i <= n; i++)
			dfs(t + 1, s + num[i], i + 1);
}
int main()
{
	cin >> n >> k;
	for (int i = 1; i <= n; i++)
		scanf("%d", &num[i]);
	dfs(0, 0, 1);
	cout << ans;
	return 0;
}

 

上一篇
下一篇