现在的位置: 首页 > 综合 > 正文

Code[vs]1008 选数( dfs+枚举判素)

2018年04月28日 ⁄ 综合 ⁄ 共 1010字 ⁄ 字号 评论关闭

1008 选数

 

2002年NOIP全国联赛普及组

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold

题目描述 Description

已知 n 个整数 x1,x2,…,xn,以及一个整数 k(k<n)。从 n 个整数中任选 k 个整数相加,可分别得到一系列的和。例如当 n=4,k=3,4 个整数分别为 3,7,12,19 时,可得全部的组合与它们的和为:

    3+7+12=22  3+7+19=29  7+12+19=38  3+12+19=34。

  现在,要求你计算出和为素数共有多少种。

  例如上例,只有一种的和为素数:3+7+19=29)。

输入描述 Input Description

 键盘输入,格式为:

  n , k (1<=n<=20,k<n)

  x1,x2,…,xn (1<=xi<=5000000)

输出描述 Output Description

屏幕输出,格式为:

  一个整数(满足条件的种数)。

样例输入 Sample Input

4 3

3 7 12 19

样例输出 Sample Output

1

数据范围及提示 Data Size & Hint

(1<=n<=20,k<n)

(1<=xi<=5000000)

解题思路:

这题其实很简单,难度不大,只需要用dfs找到任意k个数的和,然后在计算res的时候,枚举判素就可以了,具体的状态转移,大家可以自己画了。。。

代码:

# include<cstdio>
# include<iostream>

using namespace std;

# define MAX 25

int a[MAX];
int res;
int n,k;

int judge( int x )
{
    if ( x==0||x==1 )
    {
        return 0;
    }
    for ( int i = 2;i*i <= x;i++ )
    {
        if ( x%i==0 )
            return 0;
    }
    return 1;
}


void dfs( int st,int flag,int sum )
{
    if ( flag == k&&judge(sum) )
    {
        res++;
        return;
    }
    if ( st==n )
    {
        return;
    }
    for ( int i = st;i < n;i++ )
    {
        dfs(i+1,flag+1,sum+a[i]);
    }
    return;
}


int main(void)
{
    //input 4 3;3 7 12 19
    //int n,k;
    cin>>n>>k;
    for ( int i = 0;i < n;i++ )
    {
        cin>>a[i];
    }
    dfs(0,0,0);
    cout<<res<<endl;

    return 0;
}

抱歉!评论已关闭.