【题解】洛谷P1036选数[NOIP2002普及] 递归

题目链接

#include
int n,k;
int a[25];
int vis[25];
int ans;
bool judge(int sum)
{
    if(sum==1)return 0;
    for(int i=2;i*i<=sum;i++)
    if(sum%i==0)return 0;
    return 1;
}
void dfs(int id,int sum,int cnt)
{
    if(cnt==k)
    {
        if(judge(sum))ans++;
        return;
    }
    for(int i=1;i<=n;i++)
    {
        if(vis[i])continue;
        if(i<=id)continue;
        sum+=a[i];
        cnt++;
        vis[i]=1;
        dfs(i,sum,cnt);
        sum-=a[i];
        cnt--;
        vis[i]=0;
    }
}
int main()
{
    //freopen("in.txt","r",stdin);
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);
    dfs(0,0,0);
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(洛谷,NOIP,递归)