c_cpp 0-1Knapsack
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 0-1Knapsack相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h>
using namespace std;
// #DynamicProgramming #StandardProblem
// https://codingblocks.com/resources/dp-webinar/
// Testcase:
// 1
// 3
// 6 10 12
// 1 2 3
// 5
// Output: 22
// ===============( Recursion last item to first (Right to Left) )===============
int maxValueTD(vector<int> wt, vector<int> val, int cap, int lastIndex){
if(lastIndex<0){
return 0; // no items
}
if(cap==0){
return 0; // no capacity left
}
int with=0; // if wt > cap cant pickup, profit 0
if(wt[lastIndex]<=cap){
with=val[lastIndex] + maxValueTD(wt,val,cap-wt[lastIndex],lastIndex-1);
}
int without=maxValueTD(wt,val,cap,lastIndex-1);
return max(with,without);
}
int maxValueTD(vector<int> wt, vector<int> val, int cap){
int lastIndex=wt.size()-1;
return maxValueTD(wt, val, cap, lastIndex);
}
//=====================( BottomUp )=====================
int maxValueBU(vector<int> wt, vector<int> val, int cap){
int n=wt.size();
vector<vector<int>> dp(n+1,vector<int>(cap+1));
// i-> numOfItems( NOT index ), c->capacity
// bases cases
for(int i=0;i<=n;i++){
dp[i][0]=0; // capacity 0
}
for(int c=0;c<=cap;c++){
dp[0][c]=0; // no items
}
for(int i=1;i<=n;i++){
for(int c=1;c<=cap;c++){
int prev=dp[i-1][c];
int with=0;
// NOTE: wt and val have ranges [0,n-1]
// Here i denotes number of items NOT index
if(c>=wt[i-1]){ // if obj is picked up
with=val[i-1]+dp[i-1][c-wt[i-1]];
}
int without=prev; // if object is not picked stays same as for prev
dp[i][c]=max(with,without);
}
}
cout<<"BottomUp Table: "<<endl;
for(int i=0;i<=n;i++){
for(int c=0;c<=cap;c++){
cout<<dp[i][c]<<" ";
}
cout<<endl;
}
return dp[n][cap];
}
//=====================( TopDown (Left to Right) )=====================
int maxValue(vector<int> wt, vector<int> val, int cap, int index){
if(index>=wt.size()){
return 0; // no items left
}
if(cap<=0){
return 0; // no space left
}
int with=0;
if(wt[index]<=cap){
with=val[index]+maxValue(wt,val,cap-wt[index],index+1);
}
int without=maxValue(wt,val,cap,index+1);
// decide if picking/without picking gives max profit
return max(with,without);
}
int maxValue(vector<int> wt, vector<int> val, int cap){
return maxValue(wt,val,cap,0); // starting from 0 index
}
int main(){
freopen("ip.txt","r",stdin);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int> val(n);
vector<int> wt(n);
for(int i=0;i<n;i++){
cin>>val[i];
}
for(int i=0;i<n;i++){
cin>>wt[i];
}
int cap;
cin>>cap;
cout<<"Memoization: "<<maxValue(wt,val,cap)<<endl;
cout<<"BottomUp: "<<maxValueBU(wt,val,cap)<<endl;
cout<<"TopDown: "<<maxValueTD(wt,val,cap)<<endl;
}
return 0;
}
以上是关于c_cpp 0-1Knapsack的主要内容,如果未能解决你的问题,请参考以下文章