Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 42587
- 파이썬
- dfs
- Two Pointer
- 완전탐색
- frontend
- algorhtim
- DP
- configfile
- Algorithm
- javascirpt
- 좌표이동
- InfluxDB
- queue
- 1844
- 스택/큐
- summerwintercoding
- 프로그래머스
- typescript
- javascript
- 알고리즘
- modbus
- pymodbus
- data platform
- 개발브로그
- python
- set활용
- Stack
- 코딩테스트
- React
Archives
- Today
- Total
DM Log
[스택/큐] 다리를 지나는 트럭 - Python / JavaScript 본문
문제 링크 - https://school.programmers.co.kr/learn/courses/30/lessons/42583
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
[문제 간단 요약]
- 길이가 bridge_length인 다리를 트럭들이 들어간 순서대로 건너간다.
- 다리 위 트럭 총 무게는 weight를 초과할 수 없다.
- 매 초마다 트럭은 한 칸씩 전진하고, 다리 길이만큼 이동하면 빠져나온다.
- 모든 트럭이 건너는 데 걸리는 총 시간을 구하는 문제.
[문제 해결 방안]
✅ 큐(Queue) 시뮬레이션 + 슬라이딩 창(bridge)
- 다리를 길이 bridge_length의 큐로 보고, 매 초마다 popleft()로 맨 앞을 빼서 다리에서 내려오는 트럭의 무게 차감
- 트럭을 올릴 수 있으면(현재 다리 무게 + 다음 트럭 ≤ weight) 트럭 무게를 append, 아니면 0을 append
- 대기 트럭 큐가 빌 때까지 시간을 누적하고, 마지막으로 다리 위에 남아 있는 트럭들이 빠져나가도록 bridge_length 초 더하
[문제 해결 코드 - python]
from collections import deque
def solution(bridge_length, weight, truck_weights):
q = deque(truck_weights)
bridge = deque([0] * bridge_length)
time = 0
current_weight = 0
while q:
time += 1
current_weight -= bridge.popleft()
if current_weight + q[0] <= weight:
new_weight = q.popleft()
current_weight += new_weight
bridge.append(new_weight)
else:
bridge.append(0)
return time + bridge_length
[문제 해결 코드 - JavaScript]
function solution(bridge_length, weight, truck_weights) {
const waiting = [...truck_weights];
const bridgeQueue = []; // { w: 트럭무게, exit: 내려오는 시각 }
let time = 0;
let onBridge = 0;
while (waiting.length > 0 || onBridge > 0) {
time += 1;
// 내려올 차례면 내리기
if (bridgeQueue.length && bridgeQueue[0].exit === time) {
onBridge -= bridgeQueue[0].w;
bridgeQueue.shift();
}
// 다음 트럭 올릴 수 있으면 올리기
if (waiting.length && onBridge + waiting[0] <= weight && bridgeQueue.length < bridge_length) {
const w = waiting.shift();
onBridge += w;
bridgeQueue.push({ w, exit: time + bridge_length });
}
}
return time;
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[DP] 땅따먹기 - Python (3) | 2025.08.03 |
---|---|
[Summer/Winter Coding(~2018)] 방문 길이 - Python / JavaScript (1) | 2025.07.20 |
[완전탐색] 모음사전 - Python / JavaScript (0) | 2025.07.19 |
[DFS/BFS] 타겟 넘버 - Python / Javascript (1) | 2025.07.15 |
[BFS] 게임 맵 최단거리 - Python (0) | 2025.07.14 |