2428: 【普及-】【P1036】选数

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:9 解决:8

题目描述

已知 lns="http://www.w3.org/1998/Math/MathML"> 个整数 lns="http://www.w3.org/1998/Math/MathML">1,2,,,以及 lns="http://www.w3.org/1998/Math/MathML">1 个整数 lns="http://www.w3.org/1998/Math/MathML">lns="http://www.w3.org/1998/Math/MathML"><)。从 lns="http://www.w3.org/1998/Math/MathML"> 个整数中任选 lns="http://www.w3.org/1998/Math/MathML"> 个整数相加,可分别得到一系列的和。例如当 lns="http://www.w3.org/1998/Math/MathML">=4lns="http://www.w3.org/1998/Math/MathML">=3lns="http://www.w3.org/1998/Math/MathML">4 个整数分别为 lns="http://www.w3.org/1998/Math/MathML">3,7,12,19 时,可得全部的组合与它们的和为:

lns="http://www.w3.org/1998/Math/MathML">3+7+12=22

lns="http://www.w3.org/1998/Math/MathML">3+7+19=29

lns="http://www.w3.org/1998/Math/MathML">7+12+19=38

lns="http://www.w3.org/1998/Math/MathML">3+12+19=34

现在,要求你计算出和为素数共有多少种。

例如上例,只有一种的和为素数:lns="http://www.w3.org/1998/Math/MathML">3+7+19=29

输入

第一行两个空格隔开的整数 lns="http://www.w3.org/1998/Math/MathML">,lns="http://www.w3.org/1998/Math/MathML">120lns="http://www.w3.org/1998/Math/MathML"><)。

第二行 lns="http://www.w3.org/1998/Math/MathML"> 个整数,分别为 lns="http://www.w3.org/1998/Math/MathML">1,2,,lns="http://www.w3.org/1998/Math/MathML">15×106)。

输出

输出一个整数,表示种类数。

样例输入 复制

4 3
3 7 12 19

样例输出 复制

1

提示

NOIP 2002 普及组第二题






#include<bits/stdc++.h>
using namespace std;
int a[21];
int n;
bool is_prime(int x) {
	for (int i=2;i*i<=x;i++) {
		if (x%i==0) return 0;
	}
	return 1;
}
bool eval(int S) {
	int sum=0;
	for (int i=0;i<n;i++) {
		if (S&(1<<i)) sum+=a[i]; 
	}
	return is_prime(sum); 
}
int main(){
	int k,ans=0;
	cin>>n>>k;
	for (int i=0;i<n;i++) cin>>a[i];
	int U=1<<n;
	for (int S=0;S<U;S++) {
		if (__builtin_popcount(S)==k && eval(S)) ans++;
	}
	cout<<ans<<endl;
	return 0;
}