NOOJ927The partial sum problem

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=927


这也算是个0-1背包的思想的吧。加上剪枝。


代码:

#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

int n,k;
int a[25];

bool dfs(int cur,int sum)

{
    if(sum > k)
        return false;
    if(sum == k)
        return true;
    if(cur == n)
        return sum == k;
    if(dfs(cur + 1,sum))
        return true;
    if(dfs(cur + 1,sum + a[cur]))
        return true;
}

int main()

{
    while(~scanf("%d",&n))
    {
        for(int i = 0; i < n; ++i)
            scanf("%d",&a[i]);
        scanf("%d",&k);
        if(dfs(0,0))
            printf("Of course,I can!\n");
        else
            printf("Sorry,I can't!\n");
    }
}

你可能感兴趣的:(ACM,DFS,0-1背包)