@[TOC]Select the number (Luogu)
Add a link description
There are two issues to consider in this Luogu's number selection question. One is to select k numbers from n numbers, and the other is to judge whether the sum of k numbers is prime (of course, the previous problem is solved, this is not a big problem (@.@).
I use the universal dfs Deep search to solve the number selection problem, and then the answer is ready to come out. Not much nonsense, post the code below.
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int n,k,a[21],book[21]={
0},c[21],vis[10]={
0},num=0,flag=0;
set<int> it,itt;
int sushu(int n)//判断是否为素数
{
if(n==1)
return 0;
else {
for(int i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
}
void dfs(int step)//深搜
{
int i,sum=0,p=0,q=1,w=0,m;
if(step==k+1)
{
for(i=1;i<=k;i++)
sum+=c[i];
if(sushu(sum))
{
for(i=1;i<=k;i++)
{
p+=vis[i];
q=q*(vis[i]%20);
}
w=p+q;
pair<set<int>::iterator,bool> result=it.insert(w);
if(!result.second)
return;
num++;
}
return;
}
for(i=1;i<=n;i++)
{
if(book[i]==0)
{
book[i]=1;
c[step]=a[i];
vis[step]=i;
dfs(step+1);
book[i]=0;
}
}
return;
}
int main()
{
int i;
cin>>n>>k;
for(i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
dfs(1);
cout<<num<<endl;
return 0;
}
This question is Jiangzi, welcome to communicate with me~