-
Notifications
You must be signed in to change notification settings - Fork 0
/
背包问题.cpp
51 lines (42 loc) · 1.03 KB
/
背包问题.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
#include<iostream>
using namespace std;
int knapback(int n, int v, int* val, int* vol) {
int** a = new int* [n + 1];
for (int i = 0; i < n + 1; i++) {
a[i] = new int[v + 1];
}
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= v; j++) {
if (i == 0 || j == 0)
a[i][j] = 0;
else if (vol[i - 1] > j)
a[i][j] = a[i - 1][j];
else
a[i][j] = max(a[i - 1][j], a[i - 1][j - vol[i - 1]] + val[i - 1]);
}
}
int result = a[n][v];
for (int i = 0; i < n + 1; i++) {
delete[] a[i];
}
delete[] a;
return result;
}
int main()
{
int n, v;
cin >> n >> v;
int* vol = new int[n];
int* val = new int[n];
for (int i = 0; i < n; i++)
{
int volume, value;
cin >> volume >> value;
vol[i] = volume;
val[i] = value;
}
cout << knapback(n, v, val, vol) ;
delete[] vol;
delete[] val;
return 0;
}