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;

}

小结

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

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

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

相关推荐
Oneshot1 小时前
DLX(Dancing Links)算法详解:求解数独最快的算法
算法
青少儿编程课堂2 小时前
蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会Scratch考级:校园连连看解析
c++·python·算法·bfs·信息学竞赛
kongdong2 小时前
Hikyuu | RSI均值回归交易策略实现
算法·均值算法·回归·量化交易·交易策略·hikyuu
小王C语言2 小时前
优选算法:分治-归并排序
算法
非优秀程序员13 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
武子康19 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw051 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术1 天前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs1 天前
Rust LeetCode238 算法题解
开发语言·算法·rust