- Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathZeroOneKnapsackExample.java
More file actions
Latest commit
58 lines (50 loc) · 1.87 KB
/
Copy pathZeroOneKnapsackExample.java
File metadata and controls
58 lines (50 loc) · 1.87 KB
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
packagech23;
importjava.util.ArrayList;
importjava.util.List;
publicclassZeroOneKnapsackExample {
staticclassCargo {
// 가치($)
intprice;
// 무게(kg)
intweight;
publicCargo(intprice, intweight) {
this.price = price;
this.weight = weight;
}
}
publicstaticintzeroOneKnapsack(List<Cargo> cargos) {
// 용량
intcapacity = 15;
// 짐 개수 x 배낭 용량, 2차원 배열 선언
int[][] pack = newint[cargos.size() + 1][capacity + 1];
for (inti = 0; i <= cargos.size(); i++) {
// 배낭 용량을 점점 늘려가며 순회
for (intc = 0; c <= capacity; c++) {
if (i == 0 || c == 0) {
pack[i][c] = 0;
} elseif (cargos.get(i - 1).weight <= c) {
// 현재 짐 무게가 배낭 용량 이내인 경우 최대 가격 계산
pack[i][c] = Math.max(
// 현재 짐 가격 + 이전 짐의 현재 짐 무게를 뺀 용량의 가격
cargos.get(i - 1).price + pack[i - 1][c - cargos.get(i - 1).weight],
pack[i - 1][c]
);
} else {
// 용량을 넘어선 경우 이전 짐의 가격을 그대로 이관
pack[i][c] = pack[i - 1][c];
}
}
}
returnpack[cargos.size()][capacity];
}
publicstaticvoidmain(String[] args) {
List<Cargo> cargos = newArrayList<>();
cargos.add(newCargo(4, 12));
cargos.add(newCargo(2, 1));
cargos.add(newCargo(10, 4));
cargos.add(newCargo(1, 1));
cargos.add(newCargo(2, 2));
intresult = zeroOneKnapsack(cargos); // 15
System.out.println(result);
}
}