0-1 Knapsack Problem(01背包模板)

本文详细解析了01背包问题的算法实现,通过一个具体的示例介绍了如何在不超过背包容量的条件下,选择物品以达到价值最大化。文章提供了一个C++实现的代码模板,帮助读者理解和应用01背包算法。

滴答滴答---题目链接 

You have N items that you want to put them into a knapsack. Item ihas value vi and weight wi.

You want to find a subset of items to put such that:

  • The total value of the items is as large as possible.
  • The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

  • 1 ≤ N ≤ 100
  • 1 ≤ vi ≤ 1000
  • 1 ≤ wi ≤ 1000
  • 1 ≤ W ≤ 10000

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

 

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9

n,m

a,w;

题意:n个产品,不超过m重量,接下来a代表一个产品的价格,w表示一个产品的重量,输出在不超过m重量的前提下,最大得到的价格

01背包模板

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int inf=0x3f3f3f;
int dp[10010];
int a[10100],w[10010];
int main()
{memset(dp,0,sizeof(dp));
    int m,n;
    cin>>n>>m;
    for(int i=1; i<=n; i++)
        cin>>a[i]>>w[i];
    for(int i=1; i<=n; i++)
        for(int j=m; j>=w[i]; j--)
            dp[j]=max(dp[j],dp[j-w[i]]+a[i]);
    printf("%d\n",dp[m]);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值