P1036 选数 dfs

很水的dfs...不想说什么了

Codes:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 
 6 using namespace std;
 7 const int N = 20 + 5;
 8 int a[N],n,k;
 9 int ans;
10 bool vis[N];
11 bool check(int x){//判断素数 
12     if(x == 1 || x == 0) return false; //特判 
13     if(x == 2) return true;
14     for(int i = 2;i * i <= x;++ i){
15         if(x % i == 0) return false;
16     }
17     return true;
18 }
19 void dfs(int i,int j,int sum){//dfs
20     if(j > k) return;
21     if(j == k && check(sum)){
22         ans ++;
23         return;
24     }
25     else if(i <= n){
26         dfs(i + 1,j + 1,sum + a[i]);
27         dfs(i + 1,j,sum);
28     } 
29     return;
30 }
31 int main(){
32     scanf("%d%d",&n,&k);
33     for(int i = 1;i <= n;++ i){
34         scanf("%d",&a[i]);
35     }
36     dfs(1,0,0);
37     cout << ans << '
';
38     return 0;
39 }
原文地址:https://www.cnblogs.com/Loizbq/p/7657391.html