728x90
๋ฐ์ํ
โ๋ฌธ์
https://www.acmicpc.net/problem/14889
๐์ ํ
๋ฐฑํธ๋ํน
โ๐ปํ์ด
๊ณ ๋ฅด์ง ์์ ์ ์๋ผ๋ฉด true๋ก ๋ฐ๊พธ๊ณ ์ ํํ ์ ์ + 1 ๋ถํฐ ์ถ์ .
n/2๋ช
์ ๊ณ ๋ฅด๊ณ ์คํํธํ ์ ์์ ๋งํฌ ํ ์ ์๋ฅผ ๊ณ์ฐ.
๋ ๊ณ์ฐ์ ์ฐจ์ ์ ๋๊ฐ๊ณผ ์ต์๊ฐ์ ๋น๊ตํ์ฌ ๊ฐ์ฅ ์ฐจ๊ฐ ์์ ์ต์๊ฐ ์ฐพ๊ธฐ.
๐ป์ฝ๋
import java.util.*;
import java.io.*;
public class Main {
static int n;
static int min = Integer.MAX_VALUE;
static int[][] s;
static boolean[] visited;
static void backtracking(int len, int idx) {
if (len == n / 2) {
int start = 0;
int link = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (visited[i] && visited[j]) {
start += s[i][j] + s[j][i];
} else if (!visited[i] && !visited[j]) {
link += s[i][j] + s[j][i];
}
}
}
min = Math.min(min, Math.abs(start - link));
return;
}
for (int i = idx; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
backtracking(len + 1, i + 1); /** ํ์ฌ ์ธ๋ฑ์ค ์์น + 1 **/
visited[i] = false;
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
n = Integer.parseInt(r.readLine());
s = new int[n][n];
visited = new boolean[n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(r.readLine(), " ");
for (int j = 0; j < n; j++) {
s[i][j] = Integer.parseInt(st.nextToken());
}
}
backtracking(0, 0);
System.out.println(min);
}
}
๐ก์๋ก ๋ฐฐ์ด ๋ด์ฉ
์ ๋๊ฐ ํจ์๋ Math ๋ผ์ด๋ธ๋ฌ๋ฆฌ
728x90
๋ฐ์ํ
'Coding Test > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ๋ฒ ์คํธ์จ๋ฒ/Java - Lv.3 (0) | 2024.10.07 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค]์์ฃผํ์ง ๋ชปํ ์ ์/Java - Lv.1 (0) | 2024.10.06 |
[Baekjoon] 15649.N๊ณผ M (1)/Java - Silver3 (0) | 2024.09.29 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ฃผ์๊ฐ๊ฒฉ/Java - Lv.2 (0) | 2024.09.29 |
[Baekjoon] 28278. ์คํ 2/Java - Silver4 (0) | 2024.09.28 |