OpenJudge_ 简单英文题_04:0/1 Knapsack

题目

描述

Given the weights and values of N items, put a subset of items into a knapsack of capacity C to get the maximum total value in the knapsack. The total weight of items in the knapsack does not exceed C.

输入

First line: two positive integers N (N <= 100) and C (C <= 1000).

Second line: N positive integers wi (wi <= 1000), indicating the weight of the i-th item.

Third line: N positive integers vi (vi <= 1000), indicating the value of the i-th item.

输出

One line contains several integers, indicating the indexes of the selected items.

样例输入

5 10

2 4 6 2 5

1 3 4 2 8

样例输出

2

5

翻译

题目:

0/1背包

描述:

给定N个物品的权重和值,将一个子集的物品放入容量为C的背包中,以获得背包中的最大总值。背包中物品的总重量不超过C。

输入:

第一行:两个正整数N(N<=100)和C(C<=1000)。

第二行:N个正整数wi(wi<=1000),表示第i个项目的权重。

第三行:N个正整数vi(vi<=1000),表示第i项的值。

输出:

一行包含几个整数,表示所选项目的索引。

代码

#include <bits/stdc++.h>

using namespace std;

int n,//物品数量

c,//背包容量

w1001,//每物品重量

v1001,//每物品价值

f1011001;//多少重量时对应的最大价值

/*

fij=max(fi-1j,fi-1j-w\[i]+vi);

f几个物品重量=最大(f不要该物品同样重量,f不要该物品重量-该物品重量+该物品价值);

没有该重量时的最大价值+该物品价值。

*/

struct node{

int i,j;

}p1011001; //该物品的上个物品

void view(){//观察数据

cout<<"数据:\n";

cout<<"重量\t\t";for(int j=0;j<=c;j++)cout<<j<<"\t";cout<<endl;

for(int i=1;i<=n;i++){

cout<<i<<":\t"<<wi<<","<<vi<<"\t";for(int j=0;j<=c;j++)cout<<fij<<"\t";cout<<endl;

cout<<"\t\t";for(int j=0;j<=c;j++)cout<<pij.i<<","<<pij.j<<"\t";cout<<endl;

}

cout<<endl;

}

int main(){

//freopen("data.cpp","r",stdin);

cin>>n>>c;

//cout<<"物品数量"<<n<<"\t背包容量"<<c<<endl;

for(int i=1;i<=n;i++)cin>>wi;

for(int i=1;i<=n;i++)cin>>vi;

for(int i=1;i<=n;i++)//行,各物品

for(int j=0;j<=c;j++){//列,每重量

fij=fi-1j;//该重量时能取得的最大价值可以初步认定为不用该物品就取得的最大价值

pij=node{i-1,j};

if(j>=wi)//如果重量超过该物品的重量,可以考虑用该物品

if(fij<fi-1j-w\[i]+vi){//不用该物品(i-1)不算该物品重量(j-wi)时取得的最大价值上+该物品的价值

fij=fi-1j-w\[i]+vi;

pij=node{i-1,j-wi};

}

}

//view();

stack s;

int pi=n,pj=c;

while(fpipj!=0){//只要有价值就算

node px=ppipj;//找到前一状态

if(pj!=px.j)s.push(pi);//如果两状态的重量一样就不算。

pi=px.i,pj=px.j;

}

while(!s.empty()){//逆序输出采用的各物品

cout<<s.top()<<endl;s.pop();

}

return 0;

}

小结

动态规划就怕画表格,画完表格就清楚了。

初始状态是怎样,随着阶段的变化状态怎样变化。

然后就能找到动态转移方程。

相关推荐
lueluelue472 小时前
LeetCode:链表
算法·leetcode·链表
橘子汽水1685 小时前
Leetcode 23,543合并K个升序链表,二叉树的直径
算法·leetcode·链表
huameinan狮子5 小时前
Adaboost算法原理与计算实例
算法
别怪我很水5 小时前
API中提供了VelocityTracker类用于计算触摸事件MotionEvent的速度,而其内部默认使用的方法就是最小二乘法,本 ...
算法·gitee·最小二乘法
Re.不晚8 小时前
挑战做100道力扣算法- DAY1
算法·leetcode·职场和发展
蓝悦无人机8 小时前
《Planning algorithms》读书笔记——第1章 引言
算法·读书笔记·规划算法·lavalle
Sagittarius_A*9 小时前
分组密码基础(二):Feistel 结构与 DES 的设计思想
算法·信息安全·密码学·des·数论
青山木9 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
alexwang2119 小时前
HDU 4348 详细题解
c++·算法·题解·hdu·主席树·可持久化数据结构·可持久化线段树