πŸ“– [λ°±μ€€μ•Œκ³ λ¦¬μ¦˜ 풀이] Q.10819 차이λ₯Ό μ΅œλŒ€λ‘œ 문제 풀이 - java

πŸ“– 문제

https://www.acmicpc.net/problem/10819

N개의 μ •μˆ˜λ‘œ 이루어진 λ°°μ—΄ Aκ°€ 주어진닀. μ΄λ•Œ, 배열에 λ“€μ–΄μžˆλŠ” μ •μˆ˜μ˜ μˆœμ„œλ₯Ό 적절히 λ°”κΏ”μ„œ

λ‹€μŒ μ‹μ˜ μ΅œλŒ“κ°’μ„ κ΅¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€.

A[0] - A[1] + A[1] - A[2] + … + A[N-2] - A[N-1]

πŸ” 접근법

Q.10819 차이λ₯Ό μ΅œλŒ€λ‘œ λ¬Έμ œμž…λ‹ˆλ‹€.

N개의 μ •μˆ˜λ‘œ 이루어진 λ°°μ—΄ Aκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ

이 배열에 λ“€μ–΄μžˆλŠ” μ •μˆ˜μ˜ μˆœμ„œλ₯Ό 적절히 λ°”κΏ” λ‹€μŒ μ‹μ˜ μ΅œλŒ“κ°’μ„ κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

λ°°μ—΄ A의 μ •μˆ˜μ˜ μˆœμ„œλ₯Ό λ°”κΎΌ λͺ¨λ“  경우λ₯Ό 확인해 μ΅œλŒ“κ°’μ„ ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

brute force λ°©μ‹μœΌλ‘œ 풀이가 κ°€λŠ₯ν•˜κ³ 

brute force둜 λͺ¨λ“  경우λ₯Ό ν™•μΈν•˜κΈ° μœ„ν•΄

λ°±νŠΈλž˜ν‚Ήμ„ μ‚¬μš©ν•΄μ„œ 닡을 ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

λ°°μ—΄ A의 μ •μˆ˜μ— λŒ€ν•΄ λͺ¨λ“  κ²½μš°μ— λŒ€ν•΄

|A[0] - A[1]| + |A[1] - A[2]| + ... + |A[N-2] - A[N-1]|

식을 κ³„μ‚°ν•˜λ©° μ΅œλŒ“κ°’μ„ ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

πŸ’» μ½”λ“œ

package problem.brute;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main_10819 {

    static int n;
    static boolean[] visited;
    static int[] sequence,numbers;
    static int max = Integer.MIN_VALUE;

    public static void main(String[] args) throws IOException {
        input();
        dfs (1);
        System.out.println(max);
    }


    public static void input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        sequence = new int[n+1];
        numbers = new int [n+1];
        visited = new boolean[n+1];
        String [] temp = br.readLine().split(" ");
        for(int i=1; i<=n; i++){
            numbers[i] = Integer.parseInt(temp[i-1]);
        }
    }

    public static void dfs(int depth) {
        if(depth==n+1){
            caculate();
            return;
        }
        for(int i=1; i<=n; i++){
            if(!visited[i]){
                visited[i] = true;
                sequence[depth] = numbers[i];
                dfs(depth+1);
                visited[i] = false;
            }
        }
    }

    public static void caculate(){
        int sum = 0;
        for(int i=1; i<=n-1; i++){
            sum+= Math.abs(sequence[i]-sequence[i+1]);
        }
        max = Math.max(max,sum);
    }
}

Written on March 5, 2021