BOJ_S2_14889
π [S2_14889] μ€ννΈμ λ§ν¬
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[][] arr;
static boolean[] c;
static int min = Integer.MAX_VALUE;
static int res = 0;
static List<Integer> team1;
static List<Integer> team2;
static int team1_sum;
static int team2_sum;
public static void main(String[] args) throws IOException{
StringTokenizer st = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// μ¬λ μ
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
// λ½μ μ 무
c = new boolean[N];
// μ
λ ₯
for(int i=0; i<N; i++) {
st = new StringTokenizer(br.readLine(), " ");
for(int j=0; j<N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
team1 = new ArrayList<Integer>();
team2 = new ArrayList<Integer>();
comb(0,0);
System.out.println(min);
}
// μ‘°ν©
static void comb(int idx, int start) {
if(idx == N/2) {
for(int i=0; i<N; i++) {
if(c[i]) {
team1.add(i);
}
else {
team2.add(i);
}
}
// team1 ν©κ΅¬νκΈ°
for(int i=0; i<team1.size(); i++) {
for(int j=0; j<team1.size(); j++) {
team1_sum += arr[team1.get(i)][team1.get(j)];
}
}
// team2 ν©κ΅¬νκΈ°
for(int i=0; i<team2.size(); i++) {
for(int j=0; j<team2.size(); j++) {
team2_sum += arr[team2.get(i)][team2.get(j)];
}
}
// μ΅μκ° κ΅¬νκΈ°
min = Math.min(min, Math.abs(team1_sum - team2_sum));
// λλ€ μ΄κΈ°ν
team1.clear();
team2.clear();
team1_sum = 0;
team2_sum = 0;
return;
}
for(int i=start;i<N; i++) {
c[i] = true;
comb(idx+1,i+1);
c[i] = false;
}
}
}
π€ λμ μκ°
μ΄ λ¬Έμ λ μμ μκ΄ μμ΄ λͺλͺ
μ λ½μμ νμ μ΄λ£¨λ μ‘°ν© λ¬Έμ μ΄λ€.
μ²μμ ij, ji λ κ°μ ν©μ λ°°μ΄λ‘ λ°λ‘ λΊλ €κ³ μκ°νμΌλ λ±ν μ’μ μμ΄λμ΄λ μλ κ² κ°μ ν΅κ³Όνλ€.
κ·Έλ¦¬κ³ μ΄μ N λͺ
μ€μ N/2 λͺ
μ© λ½μμ booleanμ trueλ‘ μ μ₯νλ€.
true λ μ λ€μ start ν (team1) λ‘ μΉνκ³ false μΈ μ λ€μ link ν (team2) λ‘ μΉνλ€.
λ½μμ κ·Έ idxλ₯Ό listμ μ μ₯ν΄μ κ·Έ idx κ°μ κ°μ§κ³ λ°°μ΄μ μ κ·Όν΄ κ°μ λν΄μ£Όμλ€.
κ·Έλ¦¬κ³ λ ν κ°κ°μ μ μλ€μ μ΄ ν©μ λΊ κ²°κ³Όκ° κ°μ₯ μμ κ°μ μΆλ ₯ν΄μ£Όμλ€.
μ‘°ν©μ μκ³ μμΌλ©΄ μ΄λ ΅μ§ μμλ° idxλ₯Ό λΉΌμ€κ³ λν΄μ£Όκ³ μ΄ μμ
μ΄ μ’ μκ°μ΄ νμνλ κ² κ°λ€.