[BOJ] 2961 도영이가 만든 맛있는 음식

Time Lapse :3min 5sec

2961.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
import java.io.*;
import java.util.*;

public class Main {
static int[][] dp;
static int ans = 987654321, n;
static Reader r = new Reader();
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception {
dp = new int[1<<(n = r.nextInt())][2];
for(int i = 0; i < n; ++i)
ans = Math.min(Math.abs((dp[1<<i][0] = r.nextInt()) - (dp[1<<i][1] = r.nextInt())), ans);

for(int i = 0; i < n; ++i)
combination(1 << i, i);

bw.write(Integer.toString(ans));
bw.flush();
}
static void combination(int cmb, int val) {
for(int i = val + 1; i < n; ++i) {
ans = Math.min(Math.abs((dp[cmb | (1<<i)][0] = dp[cmb][0] * dp[1<<i][0]) - (dp[cmb | (1<<i)][1] = dp[cmb][1] + dp[1<<i][1])), ans);
combination(cmb | (1<<i), i);
}
}

static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
ret = (ret << 3) + (ret << 1) + (c & 0b1111);
} while ((c = read()) >= '0' && c <= '9');

return ret;
}

private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/06/PS/BOJ/2961/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.