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
键盘输入,格式为:
n , k (1<=n<=20,k<n)
x1,x2,…,xn (1<=xi<=5000000)
Output
屏幕输出,格式为:
一个整数(满足条件的种数)。
Sample Input
4 3
3 7 12 19
Sample Output
1
题解::这道题思路简单,但实现起来却遇到了问题。我不知道怎么把每一种情况都遍历一遍,在网上查看代码,发现都是用dfs来做的。在此写下自己的一点理解,加深dfs的学习。
本题的两个知识点
(1)选数(从n中选出k个)
void dfs(int t,int sum,int l){
if(t==k) {if(sum为素数)ans++;}
else
for(int i = l;i<=n;i++)
dfs(t+1,s+a[i],i+1);
}
其中t从0开始到t-1 为t个数所以当t==k是已经了k个数
l参数是为了避免一个数多次选择
dfs的运用值得学习
(2)判断素数
判断素数可以用遍历的手段,也可以先将[2,3000]之间的素数保存在数组中提高效率
bool ss(int x){
if(x == 1||x == 0)return 0;
for(int i = 2; i*i
if(x%i==0)return 0;
return 1;
}
代码::
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include