๐ ์๊ณ ๋ฆฌ์ฆ/BruteForce
[๋ฐฑ์ค] 2961๋ฒ ๋์์ด๊ฐ ๋ง๋ ๋ง์๋ ์์
์ ์ด
2021. 8. 17. 13:53
๋ฐ์ํ
๋ฌธ์
https://www.acmicpc.net/problem/2961
2961๋ฒ: ๋์์ด๊ฐ ๋ง๋ ๋ง์๋ ์์
์ฒซ์งธ ์ค์ ์ฌ๋ฃ์ ๊ฐ์ N(1 ≤ N ≤ 10)์ด ์ฃผ์ด์ง๋ค. ๋ค์ N๊ฐ ์ค์๋ ๊ทธ ์ฌ๋ฃ์ ์ ๋ง๊ณผ ์ด๋ง์ด ๊ณต๋ฐฑ์ผ๋ก ๊ตฌ๋ถ๋์ด ์ฃผ์ด์ง๋ค. ๋ชจ๋ ์ฌ๋ฃ๋ฅผ ์ฌ์ฉํด์ ์๋ฆฌ๋ฅผ ๋ง๋ค์์ ๋, ๊ทธ ์๋ฆฌ์ ์ ๋ง๊ณผ ์ด๋ง์
www.acmicpc.net
ํ์ด
์ฌ๋ฃ๋ฅผ ์กฐํฉํ์ฌ ์ด๋ง๊ณผ ์ ๋ง์ ์ฐจ์ด๋ฅผ ๊ฐ์ฅ ์ ๊ฒ ๋ง๋ค์ด์ผ ํ๋ค.
๋ฐ๋ผ์ '์กฐํฉ' ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ค.
์กฐํฉ ํ, ๊ธฐ์ ์กฐ๊ฑด์ด ๋ง์กฑํ๋ฉด ํด๋น ์กฐํฉ์ ์ ๋ง๊ณผ ์ด๋ง์ ๊ตฌํ๊ณ ์กฐํฉ ์ค ๊ฐ์ฅ ์ต์๊ฐ์ ์ฐพ๋๋ค.
์ฝ๋
import java.io.*;
import java.util.*;
public class Main{
static int n;
static int[][] tasty;
static boolean[] isSelected;
static int min=Integer.MAX_VALUE;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
tasty = new int[n][2];
isSelected = new boolean[n];
for(int i =0 ; i < n ; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
tasty[i][0] = Integer.parseInt(st.nextToken());
tasty[i][1] = Integer.parseInt(st.nextToken());
}
cook(0);
System.out.println(min);
br.close();
}
public static void cook(int cnt) {
int sour = 1;
int bitter = 0;
if(cnt == n) {
for(int i =0 ; i < n ; i++) {
if(isSelected[i]) {
sour *= tasty[i][0];
bitter += tasty[i][1];
}
}
if(sour!= 1 && bitter!=0) min = Math.min(min, Math.abs(sour-bitter));
return;
}
isSelected[cnt] = true;
cook(cnt+1);
isSelected[cnt] = false;
cook(cnt+1);
}
}
๋ฐ์ํ