YTU 2335: 0-1背包问题
来源:互联网 发布:云计算市场规模 编辑:程序博客网 时间:2024/06/05 05:40
2335: 0-1背包问题
Description
试设计一个用回溯法搜索子集空间树的函数。该函数的参数包括结点可行性判定函数和上界函数等必要的函数,并将此函数用于解0-1背包问题。 0-1 背包问题描述如下:给定n 种物品和一个背包。物品i 的重量是wi ,其价值为vi ,背包的容量为C。应如何选择装入背包的物品,使得装入背包中物品的总价值最大? 在选择装入背包的物品时,对每种物品i只有2 种选择,即装入背包或不装入背包。不能将物品i 装入背包多次,也不能只装入部分的物品i。
Input
第一行有2个正整数n和c。n是物品数,c是背包的容量。接下来的1 行中有n个正整数,表示物品的价值。第3 行中有n个正整数,表示物品的重量。
Output
将计算出的装入背包物品的最大价值和最优装入方案输出。第一行输出为:Optimal value is
Sample Input
5 106 3 5 4 62 2 6 5 4
Sample Output
Optimal value is151 1 0 0 1
HINT
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=100;
int dp[maxn][maxn];
int value[maxn];
int weight[maxn];
int x[maxn];
int main(){
int n,c;
freopen("f.txt","r",stdin);
while(~scanf("%d%d",&n,&c)){
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
scanf("%d",&value[i]);
}
for(int i=1;i<=n;i++){
scanf("%d",&weight[i]);
}
int i,j;
for(i=1;i<=n;i++){
for(j=weight[i];j<=c;j++){
dp[i][j]=max(dp[i-1][j],dp[i-1][j-weight[i]]+value[i]);
}
}
printf("Optimal value is\n%d\n",dp[n][c]);
j=c;
for(i=n;i>=0;i--){
if(dp[i][j]>dp[i-1][j]){
x[i]=1;
j-=weight[i];
}else{
x[i]=0;
}
}
for(i=1;i<=n;i++){
if(i==1) printf("%d",x[i]);
else printf(" %d",x[i]);
}
}
}
- YTU 2335: 0-1背包问题
- YTU 2335: 0-1背包问题
- YTU.2244: 背包问题(栈和队列)
- 背包问题(0-1背包、完全背包、多重背包)详解
- 背包问题和0-1背包问题
- 背包问题和0-1背包问题
- 背包问题系列--"0-1背包问题"
- 背包笔记-含0/1背包问题、完全背包问题、多重背包问题、二维背包问题、分组背包问题
- 【背包问题】背包问题之0-1背包、完全背包、多重背包
- 0-1背包问题
- 0/1背包问题
- 0,1背包问题
- 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- // 0-1背包问题
- 0/1背包问题
- 0-1背包问题
- Git操作
- poj 2533 poj3903 poj1836 最长上升子序列 LIS
- 这些小工具让你的 Android 开发更高效(下)
- Leetcode—— trapping-rain-water
- [leetcode] 8. String to Integer (atoi)
- YTU 2335: 0-1背包问题
- FZU 2218 Simple String Problem
- Activity页面跳转
- CCNA实验练习
- Linux 游戏服务器搭建教程详解
- uml类图中关联与泛化的区别
- linux用户登录日志
- Rotate Array
- Spring的自动装配(byName;byType)