-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBOJ_2961.java
More file actions
118 lines (94 loc) · 3.18 KB
/
BOJ_2961.java
File metadata and controls
118 lines (94 loc) · 3.18 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
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
/*
// 백트래킹
import java.io.*;
import java.util.*;
public class BOJ_2961 {
static int[][] flavors;
static int result = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st;
flavors = new int[n][2];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken()); // 신맛
int b = Integer.parseInt(st.nextToken()); // 쓴맛
flavors[i][0] = s;
flavors[i][1] = b;
}
boolean[] visited = new boolean[n];
int[] idx = new int[n]; // 인덱스 배열
for (int i = 0; i < n; i++) {
idx[i] = i;
}
// 조합 찾기
for (int i = 1; i <= n; i++) { // 1개 ~ n개
combination(idx, visited, 0, n, i);
}
System.out.println(result);
}
// 백트래킹 사용
static void combination(int[] arr, boolean[] visited, int start, int n, int r) {
if (r == 0) {
calculate(arr, visited, n);
return;
}
for (int i = start; i < n; i++) {
visited[i] = true;
combination(arr, visited, i + 1, n, r - 1);
visited[i] = false;
}
}
static void calculate(int[] arr, boolean[] visited, int n) {
List<Integer> idx = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (visited[i]) {
idx.add(i);
}
}
int smat = 1;
int bmat = 0;
for (int i = 0; i < idx.size(); i++) {
smat *= flavors[idx.get(i)][0];
bmat += flavors[idx.get(i)][1];
}
int answer = Math.abs((smat - bmat));
result = Math.min(result, answer);
}
}
*/
// 비트 마스킹 방법
import java.io.*;
import java.util.*;
public class BOJ_2961 {
static int[][] flavors;
static int result = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st;
flavors = new int[n][2];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken()); // 신맛
int b = Integer.parseInt(st.nextToken()); // 쓴맛
flavors[i][0] = s;
flavors[i][1] = b;
}
int lth = 1 << n; // 2의 n승 -> 부분집합의 개수
for(int i = 1; i < lth; ++i) { // 1부터 시작 -> 공집합 제외
int smat = 1;
int bmat = 0;
for (int j = 0; j < n; ++j) { // 0번째 재료, 1번째 재료...
if((i & (1 << j)) != 0) {
smat *= flavors[j][0];
bmat += flavors[j][1];
}
}
int answer = Math.abs(smat - bmat);
result = Math.min(result, answer);
}
System.out.print(result);
}
}