-
Notifications
You must be signed in to change notification settings - Fork 0
/
coins.cpp
112 lines (66 loc) · 1.82 KB
/
coins.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
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include<vector>
using namespace std;
vector<int> weights;
vector<int> getObjetosEscogidos(vector< vector<int> > dp){
vector<int> ans(dp.size(),0 );
int j = dp[0].size()-1;
int i = dp.size()-1;
while(i >0 && j> -1){
if(dp[i][j] == dp[i-1][j]) i-=1;
else{
ans[i]+=1;
j -= weights[i];
}
}
return ans;
}
int minimo(int a, int b){
if(a > 0 && b > 0){
if( a < b) return a;
return b;
}
if(a == 0) return b;
if(b == 0) return a;
}
int optimizar(int maxSize){
vector< vector<int> > dp(weights.size(), vector<int>(maxSize+1));
vector<int> objetosEscogidos(weights.size());
for(int i = 0; i < weights.size(); i++){
for(int j = 0; j<=maxSize; j++){
if(i == 0 ){
dp[i][j] = j;
}else if(j == 0)
dp[i][j] = 0;
else if(j < weights[i])
dp[i][j] = dp[i-1][j];
else
dp[i][j] = min(1 + dp[i][j - weights[i]], dp[i-1][j]);
}
}
objetosEscogidos = getObjetosEscogidos(dp);
for(int i = 0; i < dp.size(); i++){
for(int j = 0; j < dp[0].size(); j++){
cout << dp[i][j] << " ";
}
cout << endl;
}
cout << endl;
cout << "los objetos escogidos son: " << endl;
for(int i = 0; i<objetosEscogidos.size(); i++){
if(objetosEscogidos[i] > 0) cout << objetosEscogidos[i] << " de " << weights[i] << endl;
}
cout << endl;
return dp[weights.size()-1][maxSize];
}
int main(){
int n,m;
cin >> n >> m;
for(int i =0; i < n; i++){
int temp;
cin >> temp;
weights.push_back(temp);
}
cout << "el numero minimo de monedas a utilizar es: " << optimizar(m) << endl;
return 0;
}