博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AOJ 0-1 Knapsack Problem 01背包 dp
阅读量:3903 次
发布时间:2019-05-23

本文共 1294 字,大约阅读时间需要 4 分钟。

You have N items that you want to put them into a knapsack. Item i has 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 Wv1 w1v2 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 54 25 22 18 3

Sample Output 1

13

 

Sample Input 2

2 205 94 10

Sample Output 2

9

 递推关系:

dp[i][j]=max(dp[i-1][j],dp[i-1][j-b[i].w]+b[i].v);

注意要做好初始化。。。

代码如下:

#include 
#include
#include
#include
using namespace std;const int maxn=105;const int maxw=10005;int n,w;struct bag{ int v; int w;};bag b[maxn];int dp[maxn][maxw];int main(){ scanf("%d%d",&n,&w); for (int i=1;i<=n;i++) scanf("%d%d",&b[i].v,&b[i].w); for (int i=0;i<=w;i++) dp[0][i]=0; for (int i=1;i<=n;i++) dp[i][0]=0; for (int i=1;i<=n;i++) { for (int j=1;j<=w;j++) { dp[i][j]=dp[i-1][j]; if(j

 

转载地址:http://cxaen.baihongyu.com/

你可能感兴趣的文章
获取字节数
查看>>
福听阅读器 背景色设置
查看>>
保护眼睛 电脑设置
查看>>
【云端3.4 Beta】云端无法启动,从服务器返回了一个参照
查看>>
解决chrome下用google搜索图片第二页以后不显示的问题
查看>>
将163邮箱的通讯录导入到outlook2010
查看>>
winRar过期了,总弹出 “购买……”
查看>>
看过的动漫
查看>>
华硕 P5KPL-AM 前面板耳机没有声音
查看>>
个人常用的Chrome浏览器扩展程序
查看>>
labview 局部变量问题
查看>>
labview 循环外部与数组相连时问题
查看>>
哈佛大学凌晨4点半的景象--哈佛图书馆的二十条训言
查看>>
闲话机器人领域的国际会议
查看>>
Outlook2010到处通讯录
查看>>
Gmail导入通讯录
查看>>
小米笔记本安装Win 10历程
查看>>
【转】SLAM 论文阅读和分类整理
查看>>
【转】Ubuntu 16.04 重置密码(忘记密码)
查看>>
【转】信息奥赛一本通1185:单词排序(OJ题目描述有问题)
查看>>