๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[Baekjoon] 14889.์Šคํƒ€ํŠธ์™€ ๋งํฌ/Java - Silver1

by The Future Engineer, Lucy 2024. 9. 29.
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
๋ฐ˜์‘ํ˜•