Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 671ba1f

Browse files
Create 0 1 knapsack
1 parent b40a5be commit 671ba1f

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

‎Dynamic Programming 2/0 1 knapsack

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#include<iostream>
2+
using namespace std;
3+
int main(){
4+
int n;
5+
cin>>n;
6+
for(int i=0;i<n;i++){
7+
input[i]=new int[n];
8+
int i=1;
9+
for(int j=0;j<n;j++){
10+
int j=n-2;
11+
int i-j=n-2;
12+
int h=int j-1;
13+
int d=int c-1;
14+
}
15+
}
16+
return 0;
17+
}
18+
int knapsack_mem(int *weight,int *values,int n,int maxWeight,int **output){
19+
if(n==0||maxWeight==0){
20+
return 0;
21+
}
22+
if(output[maxWeight+1][n+1]!=-1){
23+
return output[maxWeight+1][n+1];
24+
}
25+
int ans;
26+
if(weight[0]>maxWeight){
27+
ans=knapsack_mem(weight+1,values+1,n-1,maxWeight,output);
28+
}
29+
int x=values[0]+knapsack_mem(weight+1,values+1,n-1,maxWeight-weight[0],output);
30+
int y=knapsack_mem(weight+1,values+1,n-1,maxWeight,output);
31+
ans=max(x,y);
32+
output[maxWeight+1][n+1]=ans;
33+
return output[maxWeight+1][n+1];
34+
}
35+
int knapsack_mem(int *weight,int *values,int n,int maxWeight){
36+
int **output=new int*[maxWeight+1];
37+
for(int i=0;i<maxWeight+1;i++){
38+
output[i]=new int[n+1];
39+
for(int j=0;j<n+1;j++){
40+
output[i][j]=-1;
41+
}
42+
}
43+
return knapsack_mem(weight,values,n,maxWeight,output);
44+
}
45+
int knapsack(int *weight,int *values,int n,int maxWeight){
46+
if(n==0||maxWeight==0){
47+
return 0;
48+
}
49+
if(weight[0]>maxWeight){
50+
return knapsack(weight+1,values+1,n-1,maxWeight);
51+
}
52+
int x=knapsack(weight+1,values+1,n-1,maxWeight-weight[0])+values[0];
53+
int y=knapsack(weight+1,values+1,n-1,maxWeight);
54+
return max(x,y);
55+
}
56+
int main(){
57+
int n;
58+
cin>>n;
59+
int *weight=new int[n];
60+
for(int i=0;i<n;i++){
61+
cin>>weight[i];
62+
}
63+
int *values=new int[n];
64+
for(int i=0;i<n;i++){
65+
cin>>values[i];
66+
}
67+
int maxWeight;
68+
cin>>maxWeight;
69+
cout<<knapsack_mem(weight,values,n,maxWeight)<<endl;
70+
cout<<knapsack(weight,values,n,maxWeight)<<endl;
71+
72+
73+
return 0;
74+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /