https://www.acmicpc.net/problem/14889
μμ μ μμ΄κ³Ό μ‘°ν© λ¬Έμ λ₯Ό μ΄μ¬ν ν λ νμ΄λ΄€λ λ¬Έμ μ΄λ€.
λ€μ νμλλ μμ λ§ν° μ νλ¦°λ€...γ
νμ 2κ°λ‘ λλ μΌ νλ―λ‘ μ‘°ν©μ μ¬μ©νμ¬ nCn/2λ₯Ό νλ©΄ λλ€.
κ·Έλ¦¬κ³ κ²°κ³Όλ₯Ό visited λ°°μ΄μ μ μ₯νμ¬ λ°©λ¬Έν νμ μ€ννΈν, μμ νμ λ§ν¬νμΌλ‘ λλ μ μλ₯Ό κ³μ°ν΄ μ£Όλ©΄ λλ€.
μ€κ°μ μκ° μ΄κ³Όκ° λ¬λλ°, μ¬κ·λΆλΆμμ combination(i + 1, count + 1)μ¬μΌ νλλ°, iλμ startλ‘ νλλ νλ Έλ€...
μ½λ
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[][] arr;
static boolean[] visited;
static int min= Integer.MAX_VALUE;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N + 1][N + 1];
visited = new boolean[N + 1];
for(int i = 1; i <= N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for(int j = 1; j <= N; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
//μ²λ¦¬
combination(1, 0); //μ‘°ν© : nCn/2
//μΆλ ₯
System.out.println(min);
}
public static void combination(int start, int count) {
if(count == N /2) {
min = Math.min(min, difference());
return;
}
for(int i = start; i < N + 1; i++) {
if(visited[i] != true) {
visited[i] = true;
combination(i + 1, count + 1);
visited[i] = false;
}
}
}
public static int difference() { //λ νμ λ₯λ ₯μΉ μ°¨μ΄
int sumStart = 0;
int sumLink = 0;
for(int i = 1; i < N + 1; i++) {
for(int j = 1; j < N + 1; j++) {
if(visited[i] && visited[j]) //μ€ννΈν
sumStart += arr[i][j];
if(!visited[i] && !visited[j]) //λ§ν¬ν
sumLink += arr[i][j];
}
}
return Math.abs(sumStart - sumLink);
}
}
κ²°κ³Ό
'Algorithm > λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€ 15686λ² - μΉν¨ λ°°λ¬ (0) | 2022.08.21 |
---|---|
λ°±μ€ 1987λ² - μνλ²³ (0) | 2022.08.18 |
λ°±μ€ 2961λ² - λμμ΄κ° λ§λ λ§μλ μμ (0) | 2022.08.16 |
λ°±μ€ 17406λ² - λ°°μ΄ λ리기 4 (0) | 2022.08.11 |
1213λ² - ν°λ¦°λ둬 λ§λ€κΈ° (0) | 2022.08.11 |