[백준 1092] 배 (JAVA)

solser12·2021년 12월 3일
0

Algorithm

목록 보기
49/56

문제


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

풀이


상자들을 정렬 후 가장 무거운 상자를 옮길 수 있는 크레인부터 자신이 옮길 수 있는 가장 무거운 상자를 맡습니다. 맡을 상자가 없으면 그냥 넘어갑니다.

만약 제일 무거운 상자를 옮길 수 있는 크레인이 제일 무거운 상자를 옮기지 못하면 -1를 출력합니다.





사용가능한 크레인 : [3, 7, 10]
상자 : [1, 3, 4, 5, 6, 8, 10]

time = 1

time = 2

time = 3

코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());
        int[] crane = new int[N];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            crane[i] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(crane);

        int M = Integer.parseInt(br.readLine());;
        Stack stack = new Stack(M);
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < M; i++) {
            stack.push(Integer.parseInt(st.nextToken()));
        }
        Arrays.sort(stack.arr);

        int time = 0;
        if (stack.peek() > crane[N - 1]) {
            time = -1;
        } else {
            Stack temp = new Stack(M);
            while (!stack.isEmpty()) {
                for (int i = N - 1; i >= 0; i--) {
                    int box;
                    while (!stack.isEmpty() && (box = stack.pop()) > crane[i]) {
                        temp.push(box);
                    }
                }

                while (!temp.isEmpty()) {
                    stack.push(temp.pop());
                }
                time++;
            }
        }

        System.out.println(time);
        br.close();
    }

    public static class Stack {
        int[] arr;
        int index;

        public Stack(int M) {
            arr = new int[M];
            index = 0;
        }

        public void push(int num) {
            arr[index++] = num;
        }

        public int pop() {
            return arr[--index];
        }

        public int peek() {
            return arr[index - 1];
        }

        public boolean isEmpty() {
            return index == 0;
        }
    }
}
profile
더 나은 방법을 생각하고 고민합니다.

0개의 댓글