zcmu-1711: 背包(dfs)

版权声明:本人大三在读,有错误烦请指正,共同进步- ( ゜- ゜)つロ 乾杯~点赞请按右上角,转载请标明出处: https://blog.csdn.net/hzyhfxt/article/details/83506353

1711: 背包

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 237  Solved: 123
[Submit][Status][Web Board]

Description

你有一个神奇的背包,他的容积是m(0<m<=80),只有你装满他,你才能拿走他,现在给你n(1<=n<=20)个物品Xi(Xi<=m),那么一共有几种方式,可以让你拿走背包?

Input

第一行 n,m

第二行 n个数字

Output

输出方案数

Sample Input

3 40 20 20 20

Sample Output

3

套了下dfs的模板~还有点小激动呢

参考博客链接(写得很详细)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <map>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
#define mem(a) memset(a,0,sizeof(a))
#define cs cout<<"-----"<<endl;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn = 1e4 + 5;
typedef long long ll;
int n,m,ans;//n:物品数目,m:背包容量
int a[25];
void dfs(int ok,int index)
{
    if(ok == 0)//能装满,算一种方案
    {
        ans++;
        return;
    }
    if(ok < 0 || index > n)//背包不能够装满
    {
        return;
    }
    else//未装满时,继续装
    {
        dfs(ok - a[index],index + 1);//计算剩余背包容量,下标++
        dfs(ok,index+1);
    }
}
int main()
{
    while(scanf("%d%d",&n,&m) != EOF)
    {
        go(i,1,n)   scanf("%d",&a[i]);
        ans = 0;
        dfs(m,1);//(背包容量,开始搜索的下标)
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hzyhfxt/article/details/83506353
今日推荐