jusung-c
으 하기싫어
jusung-c
  • 공부 기록 (96)
    • Spring (42)
      • Spring 기초 이론 (8)
      • Spring 핵심 원리 - 기본 (9)
      • Blog 만들기 with SpringBoot (25)
    • JAVA (7)
      • Java 문법 (2)
      • 객체지향의 사실과 오해 (5)
    • Algorithm (47)
      • 자료구조 (3)
      • 완전탐색 (22)
      • 정렬 (4)
      • 이분탐색 (12)
      • 투 포인터 (4)
hELLO · Designed By 정상우.
jusung-c

으 하기싫어

Algorithm/완전탐색

BOJ 10819 - 차이를 최대로

2022. 2. 28. 10:00

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

10819번: 차이를 최대로

첫째 줄에 N (3 ≤ N ≤ 8)이 주어진다. 둘째 줄에는 배열 A에 들어있는 정수가 주어진다. 배열에 들어있는 정수는 -100보다 크거나 같고, 100보다 작거나 같다.

www.acmicpc.net

아이디어

N개의 정수를 중복을 허용하지 않고 순서있게 나열하는 순열문제이다.

먼저 가능한 순열을 완전탐색을 통해 다 뽑고 난 후 주어신 식에 대입해서 최댓값을 갱신한다.

시간복잡도

N의 최댓값은 8 이므로 순열의 시간복잡도인 O(N!)에 대입하면 8! < 1초라서 가능한 접근법이다.

구현

import java.io.*;
import java.util.StringTokenizer;

public class Main {
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    static int N;
    static int[] nums, selected, visit;
    static int max = Integer.MIN_VALUE;

    public static void main(String[] args) throws IOException {
        init();

        rec_func(1);

        bw.write(max+" ");

        bw.close();
    }

    static void rec_func(int k) throws IOException {
        if (k == N + 1) {

            // 조건 식 계산
            calculate();

        } else {
            for (int i = 1; i <= N; i++) {
                int n = nums[i];

                if(visit[i] ==1) continue;

                selected[k] = n;
                visit[i] = 1;

                rec_func(k+1);

                selected[k] = 0;
                visit[i] = 0;
            }
        }
    }

    static void calculate() throws IOException {
        int sum = 0;
        for (int i = 1; i <= N-1; i++) {
            sum += Math.abs(selected[i] - selected[i+1]);
        }

//        bw.write(sum+"\n");

        max = Math.max(max, sum);

    }

    static void init() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        N = Integer.parseInt(br.readLine());

        selected = new int[N + 1];
        nums = new int[N + 1];
        visit = new int[N + 1];

        st = new StringTokenizer(br.readLine(), " ");
        for (int i = 1; i <= N; i++) {
            nums[i] = Integer.parseInt(st.nextToken());
        }

    }
}


저작자표시 비영리 변경금지 (새창열림)

'Algorithm > 완전탐색' 카테고리의 다른 글

BOJ 2529 - 부등호  (0) 2022.03.02
BOJ 2580 - 스도쿠  (0) 2022.02.28
BOJ 1759 - 암호 만들기  (0) 2022.02.27
BOJ 14888 - 연산자 끼워넣기  (0) 2022.02.25
BOJ 1182 - 부분수열의 합  (0) 2022.02.25
    'Algorithm/완전탐색' 카테고리의 다른 글
    • BOJ 2529 - 부등호
    • BOJ 2580 - 스도쿠
    • BOJ 1759 - 암호 만들기
    • BOJ 14888 - 연산자 끼워넣기
    jusung-c
    jusung-c

    티스토리툴바