问题 A: 选数
时间限制: 1 Sec 内存限制: 128 MB提交: 16 解决: 6
[ 提交][ 状态][ 讨论版]
题目描述
已知 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)。
输入
键盘输入,格式为:
n , k (1<=n<=20,k<n)
x1,x2,…,xn (1<=xi<=5000000)
输出
屏幕输出,格式为:
一个整数(满足条件的种数)。
样例输入
4 3
3 7 12 19
样例输出
1
题目链接:这里2333
#include <bits/stdc++.h> //#include <ext/pb_ds/tree_policy.hpp> //#include <ext/pb_ds/assoc_container.hpp> //using namespace __gnu_pbds; using namespace std; #define pi acos(-1) #define endl '\n' #define me(x) memset(x,0,sizeof(x)); #define foreach(it,a) for(__typeof((a).begin()) it=(a).begin();it!=(a).end();it++) typedef long long LL; const int INF=0x3f3f3f3f; const LL LINF=0x3f3f3f3f3f3f3f3fLL; const int dx[]={-1,0,1,0,-1,-1,1,1}; const int dy[]={0,1,0,-1,1,-1,1,-1}; const int maxn=1e3+5; const int maxx=5e4+6; const double EPS=1e-7; const int MOD=1000000007; #define mod(x) ((x)%MOD); template<class T>inline T min(T a,T b,T c) { return min(min(a,b),c);} template<class T>inline T max(T a,T b,T c) { return max(max(a,b),c);} template<class T>inline T min(T a,T b,T c,T d) { return min(min(a,b),min(c,d));} template<class T>inline T max(T a,T b,T c,T d) { return max(max(a,b),max(c,d));} //typedef tree<pt,null_type,less< pt >,rb_tree_tag,tree_order_statistics_node_update> rbtree; /*lch[root] = build(L1,p-1,L2+1,L2+cnt); rch[root] = build(p+1,R1,L2+cnt+1,R2);中前*/ /*lch[root] = build(L1,p-1,L2,L2+cnt-1); rch[root] = build(p+1,R1,L2+cnt,R2-1);中后*/ long long gcd(long long a , long long b){if(b==0) return a;a%=b;return gcd(b,a);} int vis[maxx],a[22],viss[22],prime[maxx],b[maxx]; int n,k,val,ans,fid; void init() { val=0; int len = sqrt(maxx) + 1; for (int i = 2; i <= len; ++i)if (!vis[i]) { prime[val++]=i; for (int j = i*i; j <= maxx; j += i)vis[j] = 1; } } int cal(int obj) { for(int i=0;i<val;i++) { if(prime[i]*prime[i]>obj) return 1; if(obj%prime[i]==0) return 0; } return 1; } int main() { init(); while(cin>>n>>k) { ans=0; for(int i=0;i<n;i++) scanf("%d",&a[i]); for(int st=0;st<(1<<n);st++)// 从0遍及到2^n-1 { int num=0,sum=0; for(int i=0;i<n;i++)//转化为二进制 { if(st&(1<<i))//& 如果这一位取了就继续下面的步骤,没取就拉闸 num++,sum+=a[i];//num表示取了多少位了 } if(num==k) if(cal(sum)) ans++;//如果满足就++ 没毛病吧 } cout<<ans<<endl; } }
&的话 1 1 就是 1;1 0就是 0;^的话 相同为1 不同为0;~的话 按位取反运算是单目运算,用来求一个位串信息按位的反,即哪些为0的位,结果是1,而哪些为1的位,结果是0。|的话 0 | 0 = 0, 0 | 1 = 1, 1 | 0 = 1, 1 | 1 = 1