import java.io.*;
import java.util.*;
public class Main {
static int N;
static int[][] S;
static boolean[] selected;
static int ans = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
S = new int[N][N];
selected = new boolean[N];
for(int i = 0; i < N; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j < N; j++){
S[i][j] = Integer.parseInt(st.nextToken());
}
}
dfs(0, 0);
System.out.print(ans);
}
static void dfs(int idx, int size){
if (size == N / 2) {
ans = Math.min(ans, calculateDifference());
return;
}
for(int i = idx; i < N; i++){
selected[i] = true;
dfs(i + 1, size + 1);
selected[i] = false;
}
}
static int calculateDifference(){
int start = 0;
int link = 0;
for(int i = 0; i < N; i++){
for (int j = 0; j < N; j++) {
if (selected[i] && selected[j]) {
start += S[i][j];
} else if (!selected[i] && !selected[j]) {
link += S[i][j];
}
}
}
return Math.abs(start - link);
}
}
조건식
for(int i = 0; i < N; i++){
if (selected[i]) {
for (int j = 0; j < N; j++) {
if (selected[j]) {
start += S[i][j];
}
}
} else {
for (int j = 0; j < N; j++) {
if (!selected[j]) {
link += S[i][j];
}
}
}
}
- 처음엔 이렇게 스파게티 코드로 작성 -> 비효율적
for(int i = 0; i < N; i++){
for (int j = 0; j < N; j++) {
if (selected[i] && selected[j]) {
start += S[i][j];
} else if (!selected[i] && !selected[j]) {
link += S[i][j];
}
}
}