
문제
https://www.acmicpc.net/problem/13335
풀이
https://whiporithm.tistory.com/131
LV2 - 다리를 지나는 트럭 (Java)
문제 https://school.programmers.co.kr/learn/courses/30/lessons/42583 프로그래머스코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이
whiporithm.tistory.com
이 문제와 완전 동일하다!
코드
import java.util.*;
import java.io.*;
/**
* [문제] (https://www.acmicpc.net/problem/13335)
*/
public class Main {
public void solution() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st1 = new StringTokenizer(br.readLine());
StringTokenizer st2 = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
int time = 0;
int n = Integer.parseInt(st1.nextToken());
int bridgeLength = Integer.parseInt(st1.nextToken());
int L = Integer.parseInt(st1.nextToken());
List<Integer> weights = new ArrayList<>();
while (st2.hasMoreTokens()) {
weights.add(Integer.parseInt(st2.nextToken()));
}
// 0으로 다리를 채워준다.
Deque<Integer> bridge = new ArrayDeque<>(bridgeLength);
for(int i=0; i<bridgeLength; i++){
bridge.offerLast(0);
}
int truckIdx = 0;
int currentWeight = 0;
while (truckIdx < n) {
int truck = weights.get(truckIdx);
int frontTruck = bridge.peekFirst();
int finalWeight = currentWeight - frontTruck + truck;
// 트럭이 더 이상 올라갈 수 없다면
if(finalWeight > L){
currentWeight -= bridge.removeFirst();
bridge.addLast(0); // 무의미한 값을 넣어준다.
time++;
continue;
}
// 트럭이 올라갈 수 있는 경우
currentWeight += truck;
currentWeight -= bridge.removeFirst();
bridge.addLast(truck);
time++;
truckIdx++;
}
while(!bridge.isEmpty()){
bridge.removeFirst();
time++;
}
sb.append(time);
System.out.println(time);
}
public static void main(String[] args) throws Exception {
new Main().solution();
}
}
후기
- 백준을 자바로 처음 풀어보는겸 풀어보았다.
- 같은 문제를 프로그래머스에서 풀었는데 조금씩 다르게 푼 게 신기하다.
- 입력 출력이 어렵다..
'백준' 카테고리의 다른 글
14719 - 빗물 (Java) (0) | 2024.08.12 |
---|---|
2615 - 오목 (Java) (0) | 2024.08.11 |
23290 - 마법사 상어와 복제 (0) | 2023.08.11 |
21611 - 마법사 상어와 블리자드 (0) | 2023.08.10 |
23288 - 주사위 굴리기 2 (0) | 2023.08.08 |