STUDY/Algorithm

[프로그래머스] LEVEL2 다리를 지나는 트럭,python3, 스택/큐

sinawi95 2019. 10. 22. 16:17
728x90

def solution(bridge_length, weight, truck_weights):
    answer = 0
    ing=[]  # 다리를 건너는 트럭
    cnt=[]  # 트럭당 지난 거리
    ed=[]   # 다리를 지난 트력
    
    while 1:
        if (truck_weights == []) and (ing == []):
            break
        answer+=1   # count total time
        for i in range(len(cnt)):       # decrease the times of trucks above the bridge
            cnt[i]-=1
            
        if (cnt!=[])and(cnt[0]==0):
            ed.append(ing[0])
            del cnt[0]
            del ing[0]
            
        if (sum(ing)<=weight) and (truck_weights != []): # compare a sum of truck and weight of bridge
            if (sum(ing)+truck_weights[0])<=weight:
                ing.append(truck_weights[0])    # add truck to ing
                cnt.append(bridge_length)       # count distances of truck
                del truck_weights[0]
        
    return answer


타인의 코드 중 가장 괜찮아보이는것을 가져왔다.

def solution(bridge_length, max_weight, truck_weights):
    # FIFO 문제.
    bridge = [0]*bridge_length
    curr_weight = 0
    ans = 0
    while len(truck_weights) > 0:
        ans += 1
        ar = bridge.pop(0)
        curr_weight -= ar
        if curr_weight + truck_weights[0] > max_weight:
            bridge.append(0)            
        else:
            truck = truck_weights.pop(0)
            bridge.append(truck)
            curr_weight += truck
    while curr_weight > 0:
        ans += 1
        ar = bridge.pop(0)
        curr_weight -= ar
    return ans