-
Notifications
You must be signed in to change notification settings - Fork 40
/
dp_min-knapsack.cpp
101 lines (68 loc) · 1.81 KB
/
dp_min-knapsack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<bits/stdc++.h>
using namespace std;
int mincheck(int a , int b){
if(a<=0)
return b;
else if(b<=0)
return a;
else return -1;
}
void minmoney(int n, int capacity , int price[]){
int dp[n][capacity];
//cout<<price[n];
// cout<<"hey0\n";
for(int i=0;i<=n;i++){
for(int j=0;j<=capacity;j++){
// cout<<"hey1\n";
if(i==0||j==0){
cout<<dp[1][5]<<"hey\n"<<i<<j;
dp[i][j]=0;
cout<<dp[1][5]<<"hey2\n";
}
else if(price[i]==-1){
dp[i][j]=-1;
}
else{
// cout<<"hey2\n";
if(dp[i-1][j]==-1||dp[i-1][j]==0){
// cout<<"hey3\n";
if(dp[i][j%i]==-1||j<i){
dp[i][j]=-1;
}
else {
dp[i][j] = price[i]*(j/i) + dp[i][j%i];
//cout<<i<<" "<<j<<" - "<<dp[i][j]<<endl;
}
}
else{
// cout<<"hey4\n";
if(dp[i][j%i]==-1||j<i){
dp[i][j]= dp[i-1][j];
}
else {
dp[i][j]= min(price[i]*(j/i) + dp[i][(j%i)], dp[i-1][j]);
}
}
}
}
// cout<<dp[1][5]<<"hey\n";}
// cout<<dp[1][5]<<"hey\n";
}
cout<<dp[1][5]<<"hey\n";
for(int i=0;i<=n;i++){
for(int j=0;j<=capacity;j++){
cout<<dp[i][j]<<" ";
}
cout<<endl;
}
cout<<dp[n][capacity];
}
int main(){
int n , capacity;
cin>>n>>capacity;
int price[n];
for(int i=1;i<=n;i++){
cin>>price[i];
}
minmoney(n , capacity , price);
}