BOJ_S2_2961
π [S2_2961] λμμ΄κ° λ§λ λ§μλ μμ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static StringTokenizer st;
// λΆλΆμ§ν© ν©μμ 체ν¬
static boolean[] isChecked;
// μ λ§, μ΄λ§ λ°°μ΄
static int[] S, B;
// μ¬λ£μ κ°μ
static int N;
static int res = Integer.MAX_VALUE;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// μ¬λ£μ κ°μ
N = Integer.parseInt(br.readLine());
// μ λ§ λ°°μ΄
S = new int[N];
// μ΄λ§ λ°°μ΄
B = new int[N];
// λΆλΆμ§ν© ν©μμ 체ν¬
isChecked = new boolean[N];
// μ
λ ₯
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine(), " ");
// μ¬λ£μ μ λ§ S -> *
S[i] = Integer.parseInt(st.nextToken());
// μ¬λ£μ μ΄λ§ B -> +
B[i] = Integer.parseInt(st.nextToken());
}
go(0);
sb.append(res);
System.out.println(sb);
}
// λΆλΆμ§ν© ν©
static void go(int start) {
int S_sum = 1;
int B_sum = 0;
int minus = 0;
int cnt =0;
// κΈ°μ 쑰건
if (start == N) {
// true λ©΄ κ³μ°μ νλ€
for (int i = 0; i < N; i++) {
if (isChecked[i]) {
cnt++;
S_sum *= S[i];
B_sum += B[i];
}
else {
continue;
}
}
if(cnt == 0) {
return;
}
minus = Math.abs(S_sum - B_sum);
res = Math.min(minus, res);
return;
}
isChecked[start] = true;
go(start + 1);
isChecked[start] = false;
go(start + 1);
}
}
π€ λμ μκ°
μ΄ λ¬Έμ λ λΆλΆ μ§ν© ν©μ ν΅ν΄ μ½κ² ν μ μμλ€.
κ·Έλ¬λ 곡μ§ν©μ μμλ€ λλ¬Έμ μ½κ° λ²λ²
μ΄κΈ΄ νλ€.