CodeVS 1008 选数(DFS)

题目大意:

 http://codevs.cn/problem/1008/

 

解题:

#include <iostream>
#include <cmath>
using namespace std;

int n ,k ;
int arr[21];
int res;

bool isPrime(int a)
{
    for(int i = 2; i < sqrt(a)+1; i++)
        if(a % i == 0)
            return false;
    return true;
}

void search(int start,int count,int total)
{
    if(count == k && isPrime(total))
        res++;
    if(count == k && isPrime(total) == false)
        return;
    if(count > k )
        return;

    for(int i = start; i < n; i++)
    {
        total += arr[i];
        count++;
        search(i+1,count,total);
        count--;
        total -=arr[i];

    }
}

int main()
{

    cin >> n >> k;
    for(int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }


    res = 0;
    search(0,0,0);
    cout << res << endl;

    return 0;
}

 

posted @ 2017-08-25 08:42  prog123  阅读(212)  评论(0编辑  收藏  举报