백준 13335 트럭 - 구현

이진중·2024년 3월 8일
0

알고리즘

목록 보기
75/76

문제 : https://www.acmicpc.net/problem/13335

구현문제 풀이

개인적인 스타일로는 구현은 손코딩을 최대한 많이 해놓고 실제 코딩하는게 구조를 기억하고 전체적인 그림에서 하나씩 차근차근 나아가기 좋았다.

t=0으로 시작해서 1씩 올릴지, 1을 올리기 전에 조건을 어떻게 설정할지 세세한 부분까지 최대한 생각하고 구현하고 코드로 옮기자.

놓친점 1 : 배열밀기 문제

for (int i = 0; i <= l-2; i++) {
                visited[i] = visited[i+1];
            }

이런식의 배열밀기 문제에서는 마지막 오른쪽 원소를 잘 신경쓰자.
visited[l-1] = ...

놓친점 2 : 큐 사용시 poll, peek 조건체크

poll, peek 사용시 empty상태는 아닌지, 잘 확인하고 사용하자.

if (!queue.isEmpty() && sumWei + queue.peek() <= w){
                visited[l-1] = queue.poll();
            }

놓친점 3 : 반복문 조건

반복문에서 조건을 사용할땐 while(!(종료조건)) 으로 생각하면 편하다.

while(!(queue.isEmpty() && sumWei == 0)){ ... }

최종 코드

import java.util.*;


/*

N = 15

15^2  = 225칸



 */
public class Main {



    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        String[] inp = sc.nextLine().split(" ");
        int n = Integer.parseInt(inp[0]);
        int l = Integer.parseInt(inp[1]);
        int w = Integer.parseInt(inp[2]);

        inp = sc.nextLine().split(" ");


        Queue<Integer> queue = new LinkedList<>();

        for (int i = 0; i < n; i++) {
            int num = Integer.parseInt(inp[i]);
            queue.add(num);
        }

        int[] visited = new int[l];

        int sumWei = 0;
        int time = 0;
        while(!(queue.isEmpty() && sumWei == 0)){
            time ++;

            sumWei -= visited[0];

            for (int i = 0; i <= l-2; i++) {
                visited[i] = visited[i+1];
            }
            visited[l-1] = 0;

            if (!queue.isEmpty() && sumWei + queue.peek() <= w){
                visited[l-1] = queue.poll();
            }

            sumWei += visited[l-1];
        }

        System.out.println(time);
    }

}

0개의 댓글