-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDividingCoins.java
108 lines (96 loc) · 2.83 KB
/
DividingCoins.java
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
/** #dynamic-programming #01knapsack */
import java.util.Scanner;
public class DividingCoins {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
for (int t = 0; t < testcase; t++) {
int n = sc.nextInt();
int w = 0;
int c, p, T;
int[] arr = new int[n + 1];
Item[] items = new Item[n + 1];
items[0] = new Item(0, 0);
for (int i = 1; i <= n; i++) {
arr[i] = sc.nextInt();
w += arr[i];
}
for (int i = 1; i <= n; i++) {
items[i] = new Item(arr[i], arr[i]);
}
int result = Knapsack(items, w / 2);
System.out.println(Math.abs(w - 2 * result));
}
}
public static int Knapsack(Item[] arr, int W) {
int[][] K = new int[arr.length][W + 1];
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j <= W; j++) {
if (arr[i].cost > j) {
K[i][j] = K[i - 1][j];
} else {
int tmp1 = arr[i].profit + K[i - 1][j - arr[i].cost];
int tmp2 = K[i - 1][j];
K[i][j] = Math.max(tmp1, tmp2);
}
}
}
return K[arr.length - 1][W];
/* refactor
Case 1:
int[][] K2 = new int[2][W + 1] => reduce space. arr.length -> 2
for (int i=1; i < arr.length; i++) {
int cur = i & 1
int prev = 1 - cur; // (i - 1) & 1
->>>> cur/prev ~ i/ i-1
..
}
Case 2:
for (int i=1; i < arr.length; i++) {
// int cur = i & 1
// int prev = 1 - cur;
for (int j=W; j >= 0; j++) { => duyet ngc, giam space. k thay doi gia tri cu..
if (arr[i].cost > j) {
K[j] = K[j];
}
else {
int tmp1 = arr[i].profit + K[j - arr[i].cost];
int tmp2 = K[j];
K[j] = Math.max(tmp1, tmp2);
}
}
}
*/
/*
Case 3:
=> reduce space...
K[j] = true/false
K[0] = true
K[j] = true
K[j - a[i]] = true
K[0] = true
for (int i=1; i < arr.length; i++) {
for (int j=W; j >= 0; j++) { => duyet ngc, giam space. k thay doi gia tri cu..
if (arr[i].cost <= j) {
bool tmp1 = K[j - arr[i].cost];
bool tmp2 = K[j];
K[j] = tmp1 || tmp2;
}
}
}
for (int i = W; i >= 0; i--) {
if (K[i] == true) {
return i
}
}
*/
}
}
class Item {
int profit;
int cost;
Item(int profit, int cost) {
this.profit = profit;
this.cost = cost;
}
}