题解:P1036 [NOIP 2002 普及组] 选数

· · 题解

感谢大佬 \color{orange}ybw0731 提出比较玄学的建议。

前置知识

本题关联题目。

算法实现很简单,我们只需考虑对一个数字选和不选。

AC 1 code

下面这个代码不用管,里面有很多玄学的东西,真正的代码是
[这个](https://www.luogu.com.cn/article/78d2ancd/edit/#AC 2 code)
#include<bits/stdc++.h>
using namespace std;
int m,n,a[25],sum,xxx=1;
map<int,int>ss;
bool SS(int k){
    if(k==1)
        return false;
    for(int i=2;i<sqrt(k);i++){
        if(k%i==0)
            return false;
    }
    return true;
}
void dfs(int x,int t,int xxx){
    if(x>m){
        if(SS(t)==true)
            sum++;
        return;
    }
    for(int i=xxx;i<=n;i++){
        dfs(x+1,t+a[i],i+1);
    }
}
signed main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    dfs(1,0,1);
    printf("%d",sum);
}

AC 2 code