中南林业科技大学第十一届程序设计大赛- I:背包问题

链接:https://www.nowcoder.com/acm/contest/124/I
来源:牛客网

时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

01背包是是一个普通的动态规划入门问题:

一共有n个物品, 第i个物品的体积为v[i];

有一个背包容量为m,现在我要挑选一些物品放入这个背包

我现在知道在总体积不超过背包容量的情况下,他一共有多少种放法(总体积为0也算一种放法)。

1 <= n <= 30, 1 <= m , v[i]<= 1e9

这就是一个很简单的01背包问题,我可以告诉你核心代码怎么写:

很简单吧,但是……,你试一试吧。


输入描述:

输入有多组,每一组第一行是n和m

接下来第二行到第n+1行,第i+1行表示v[i]。
 
  

输出描述:

输出每个样例的方案数,每个答案占据一行。
示例1

输入

复制
3 10
1
2
4

输出

复制
8

和贪心没啥关系,直接深搜列举能放下的物品就可以。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#define ll long long
#define INF 0x3f3f3f3f
const int maxn=50;
int a[maxn];
int ans;
int n,m;
void dfs(int x,int sum)
{
	if(x==n)
	{
		ans++;
		return;
	}
	dfs(x+1,sum);
	if(sum+a[x]<=m)
		dfs(x+1,sum+a[x]);
}
int main(int argc, char const *argv[])
{
	
	while(~scanf("%d%d",&n,&m))
	{
		ans=0;
		memset(a,0,sizeof(a));
		for(int i=0;i<n;i++)
			scanf("%d",&a[i]);
		dfs(0,0);
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wang_123_zy/article/details/80850038