2023-11-12
트럭
https://www.acmicpc.net/problem/13335
최대 중량이 정해진 다리를 트럭들이 건너는데 걸리는 시간을 구하는 문제
큐에 0처럼 허수를 넣어주는 것이 핵심 '키로거' 문제랑 비슷하게 연상해서 풀면 됨
내가 푼 답변
from collections import deque # n(트럭 수), w(다리 길이), l(다리의 최대하중) n, w, l = map(int, input().split()) weight_list = deque(map(int, input().split())) bridge = deque([0] * w) time = 0 while True: if len(weight_list) == 0 and sum(bridge) == 0: break bridge.popleft() time += 1 if weight_list: if sum(bridge) + weight_list[0] <= l: bridge.append(weight_list.popleft()) else: bridge.append(0) print(time)
다른 답변
from collections import deque # 트럭의 수, 다리의 길이, 최대 하중 입력 n, w, l = map(int, input().split()) trucks = list(map(int, input().split())) trucks.reverse() # 트럭 배열을 역순으로 조정 # 덱(deque)을 큐로 사용 q = deque() total = 0 # 다리 위 트럭의 총 무게 t = 0 # 총 소요 시간 while True: # 모든 트럭을 처리한 경우, 반복문 종료 if len(trucks) == 0 and total == 0: break # 큐(다리)가 가득 찬 경우 맨 앞 트럭을 꺼냄 if len(q) == w: x = q.popleft() total -= x # 트럭이 들어갈 수 있는 경우 if len(trucks) > 0 and total + trucks[-1] <= l: q.append(trucks[-1]) # 트럭을 큐(다리)에 추가 total += trucks[-1] # 총 무게 반영 trucks.pop() # 처리한 트럭 제거 else: # 다리에 트럭이 들어가지 못하는 경우, 0을 삽입 q.append(0) t += 1 # 시간 증가 print(t) # 총 소요 시간 출력
