배움 저장소

[프로그래머스] 다리를 지나는 트럭 C++ 본문

PS/프로그래머스

[프로그래머스] 다리를 지나는 트럭 C++

시옷지읏 2021. 4. 10. 21:30

programmers.co.kr/learn/courses/30/lessons/42583

 

코딩테스트 연습 - 다리를 지나는 트럭

트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이

programmers.co.kr

자료구조 공부할 때 배웠던 circular queue가 생각나 직접 구현하고 싶었다.

사이즈가 꽉 차면 자동적으로 처음 들어온 자료를 지우는 형태로 enqueue를 구현하였다.

코드를 짤 때 이미 들어가있는 자료를 지우면 weight를 초과하는지 아닌지를 체크하지 않아 고생했다.

질문하기 탭에서 Edge케이스를 해결할 수 있는 예제를 실행해보고서 위와 같은 문제가 생김을 알고 고쳤다.

#include <string>
#include <queue>
#include <vector>
using namespace std;

struct que{
    int front,len;
    vector<int> bridge;
    int sum,max_sum;

    que(int lengh, int weight){
        front=0,sum=0;

        len = lengh;
        max_sum = weight;
        bridge = vector<int>(len,0);
    }

    void enqueue(int truck){
        if(front==len || bridge[front]!=0 ){
            front%=len;
            sum -= bridge[front];
        }
        bridge[front++] = truck;
        sum+=truck;
    }
};

int solution(int bridge_length, int weight, vector<int> truck) {

    que q(bridge_length, weight);
    int time=0;
    for(int i=0; i<truck.size(); ++i){
        while(true){
            time++; 
            if(q.sum-q.bridge[q.front%q.len]+truck[i]<=weight) break;

            else q.enqueue(0);
        }
        q.enqueue(truck[i]);

        if(i==truck.size()-1)
            return time+bridge_length;
    }
    return -1;
}
Comments