51Nod1085 0-1背包(一维和二维数组实现)

版权声明:本文为博主原创文章,转载需注明出处。 https://blog.csdn.net/zz_Caleb/article/details/80671260

背包是典型的动态规划问题,关于背包问题的详解,推荐博客:点击打开链接(这篇博客有点错误,代码for循环里错了,不过讲解 的很详细)

题目如下:

在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。

Input 第1行,2个整数,N和W中间用空格隔开。N为物品的数量,W为背包的容量。(1 <= N <= 100,1 <= W <= 10000)
第2 - N + 1行,每行2个整数,Wi和Pi,分别是物品的体积和物品的价值。(1 <= Wi, Pi <= 10000) Output 输出可以容纳的最大价值。 Sample Input
3 6
2 5
3 8
4 9
Sample Output
1

二维的太大的话容易超内存,写小了容易WA,建议写一维的。

下面是二维的代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
const int Max=10005;
int w[105],p[105],f[105][Max]; //f的第二维要开大点,因为下面for循环第二维是从0一直到V
using namespace std;
int main()
{
	int n,V;
	scanf("%d%d",&n,&V);
	memset(f,0,sizeof(f));
    for(int i=1;i<=n;i++)
		scanf("%d%d",&w[i],&p[i]);
	for(int i=1;i<=n;i++){
		for(int v=0;v<=V;v++){
			if(v<w[i]) f[i][v]=f[i-1][v];
			else f[i][v]=max(f[i-1][v],f[i-1][v-w[i]]+p[i]);
		}
	}
	printf("%d",f[n][V]); 
	return 0;
}

然后是一维的代码:

#include<cstdio>
#include<algorithm>
#include<cstring> 
using namespace std;
const int Max=10500;
int w[105],p[105],f[Max]; //f要开大一点,因为下面for循环v是逐一取值递减
int main()
{
	int n,V;
	scanf("%d%d",&n,&V);
	memset(f,0,sizeof(f));
    for(int i=1;i<=n;i++)
		scanf("%d%d",&w[i],&p[i]);
	for(int i=1;i<=n;i++){
		for(int v=V;v>=w[i];v--){
			f[v]=max(f[v],f[v-w[i]]+p[i]);
		}
	}
	printf("%d",f[V]); 
}

猜你喜欢

转载自blog.csdn.net/zz_Caleb/article/details/80671260
今日推荐