选数 (dfs)

看了题懵了会儿(菜鸡的日常),有回溯的味道但又不是全排列,然后既然不是回溯还能干嘛只能用最朴素的dfs了,维护每次dfs的起点就完了。
附代码:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int A[10005];  int B[10005]; int n,m; int k=0;
bool pand(){
    int t=0;
    for(int i=0;i<m;i++){
        t+=B[i];
    }
    for(int i=2;i<=sqrt(t);i++){
        if(t%i==0) return false;
    }
    return true;
}
void dfs(int a,int b){
    if(b==m){
        if(pand()){
            k++; return ;
        }
    }
    for(int i=a;i<n;i++){
        B[b]=A[i];
        dfs(i+1,b+1);//直接dfs不用回溯
    }
}
int main(){
    cin>>n>>m;
    for(int i=0;i<n;i++){
        cin>>A[i];
    }
    dfs(0,0);
    cout<<k<<endl;
}

题目出处

发布了24 篇原创文章 · 获赞 2 · 访问量 460

猜你喜欢

转载自blog.csdn.net/chineseherofeng/article/details/104724340