Option number P1036 (DFS Dafa is good!)

https://www.luogu.com.cn/problem/P1036

Here Insert Picture Description
Here Insert Picture Description

  • If this question with dfs algorithm, which is the first track I wrote dfs algorithm problem, really understand what it means.
#include<iostream>
using namespace std;
int tot,a[25];
int n,k;
bool prime(int n)
{
    for(int i = 2;i*i <= n;i++)
        if(n%i==0)
            return 0;
    return 1;
}
void dfs(int m,int sum,int be)
{
    if(m == k&&prime(sum))//判断是否已经到了递归重点,并且满足之和为质数
    {
        tot++;//如果满足则递增计数器
        return;//返回函数

    }
    for(int i = be;i <= n;i++)//每一层进行选择,这里的选择不需要一个bool数组标记
    {//是否已经选取过,因为dfs函数中第三个参数保证了每次选取的起点都是不一样的,保证了不重不漏
        dfs(m+1,sum+a[i],i+1);//进入下一层递归!
    }
    return;
}
int main()
{
    cin >> n >> k;
    for(int i = 1;i <= n;i++)
        cin >> a[i];
    dfs(0,0,1);
    cout << tot;
}

In order to ensure that no repetition, to comply with the principle of incremental number, that is to say, there can be 1, 2, but no longer appears in 1,3,2 recursive, so you can avoid them and repeat of 6! ! !
In the method dfs, is a first determined whether the number k to the first, i.e. whether a recursive-k layer to the first, if not, proceeds to the next cycle, from the very beginning, each layer has a recursive split! ! !

Published 395 original articles · won praise 52 · views 50000 +

Guess you like

Origin blog.csdn.net/dghcs18/article/details/104333772