-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathknapsack_01_prb.cpp
125 lines (109 loc) · 2.33 KB
/
knapsack_01_prb.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# include <cstdlib>
# include <iostream>
# include <iomanip>
# include <cmath>
using namespace std;
# include "knapsack_01.hpp"
int main ( );
void test01 ( );
//****************************************************************************80
int main ( )
//****************************************************************************80
//
// Purpose:
//
// KNAPSACK_01_TEST tests the KNAPSACK_01 library.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 22 August 2014
//
// Author:
//
// John Burkardt
//
{
timestamp ( );
cout << "\n";
cout << "KNAPSACK_01_TEST\n";
cout << " C++ version.\n";
cout << " Test the KNAPSACK_01 library.\n";
test01 ( );
//
// Terminate.
//
cout << "\n";
cout << "KNAPSACK_01_TEST\n";
cout << " Normal end of execution.\n";
cout << "\n";
timestamp ( );
return 0;
}
//****************************************************************************80
void test01 ( )
//****************************************************************************80
//
// Purpose:
//
// TEST01 seeks a solution of the 0/1 Knapsack problem.
//
// Discussion:
//
// In the 0/1 knapsack problem, a knapsack of capacity C is given,
// as well as N items, with the I-th item of weight W(I).
//
// A selection is "acceptable" if the total weight is no greater than C.
//
// It is desired to find an optimal acceptable selection, that is,
// an acceptable selection such that there is no acceptable selection
// of greater weight.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 23 August 2014
//
// Author:
//
// John Burkardt
//
{
int c;
int i;
int n = 6;
int *s;
int t;
int w[6] = {
16, 17, 23, 24, 39, 40 };
c = 100;
cout << "\n";
cout << "TEST01:\n";
cout << " Knapsack maximum capacity is " << c << "\n";
cout << " Come as close as possible to filling the knapsack.\n";
s = knapsack_01 ( n, w, c );
cout << "\n";
cout << " # 0/1 Weight\n";
cout << "\n";
for ( i = 0; i < n; i++ )
{
cout << setw(4) << i << " "
<< setw(1) << s[i] << " "
<< setw(4) << w[i] << "\n";
}
t = 0;
for ( i = 0; i < n; i++ )
{
t = t + s[i] * w[i];
}
cout << "\n";
cout << " Total: " << t << "\n";
delete [] s;
return;
}