HDU--2602 (0-1背包)


Problem Description
Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave … The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ?
Input
The first line contain a integer T , the number of cases. Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output
One integer per line representing the maximum of the total value (this number will be less than 231).

Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1

Sample Output
14
#include<iostream>
using namespace std;

#define N 1010
int w[N],v[N],f[N][N]; //f[i][j]---背包容量为j存放前i件物品的最大价值

int main()
{
	
	int vol,i,num,t;  //num---物品的数量,vol---背包的容量,value--背包的最大价值
	cin>>t;
	while(t--)
	{
		memset(f,0,sizeof(f));
		cin>>num>>vol;
		for(i=1;i<=num;i++)
			cin>>v[i];
		for(i=1;i<=num;i++)
			cin>>w[i];
		for(i=1;i<=num;i++)
			for(int j=vol;j>=0;j--)
			{
				if(j>=w[i]) f[i][j]=max(f[i-1][j],f[i-1][j-w[i]]+v[i]);
				else f[i][j]=f[i-1][j];
			}
		cout<<f[num][vol]<<endl;
		
	}
	return 0;
}


注:全局变量在静态存储区分配内存,局部变量是在栈上分配内存空间的

VC堆栈默认是1M


上述代码也可用一维数组(备忘录记录区--dp[N])
#include<iostream>
using namespace std;

#define N 1010
int w[N],v[N],dp[N]; //f[i][j]---背包容量为j存放前i件物品的最大价值

int main()
{
	
	int vol,i,num,t;  //num---物品的数量,vol---背包的容量,value--背包的最大价值
	cin>>t;
	while(t--)
	{
		memset(dp,0,sizeof(dp));
		cin>>num>>vol;
		for(i=1;i<=num;i++)
			cin>>v[i];
		for(i=1;i<=num;i++)
			cin>>w[i];
		for(i=1;i<=num;i++)
			for(int j=vol;j>=w[i];j--)
			{
				dp[j]=max(dp[j],dp[j-w[i]]+v[i]);
			}
		cout<<dp[vol]<<endl;
		
	}
	return 0;
}

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn