Make Unreal REAL.
article thumbnail
Level 2. 다리를 지나는 트럭

 

 

처음에 다리를 정해진 순서로 건너간다는 말이 그냥 있는 말인 줄 알았는데, 정렬해 순서를 바꾸지 말고 입력을 그대로 쓰라는 말이었어서 조금 헷갈렸다.

  • 만약, 크기 순으로 정렬하는 문제였다면 투 포인터로 풀 수 있었을 것이다.

 

다리 길이 크기의 큐를 만들고 현재 적재 중량을 관리해 다리에 추가할 수 있을 때는 무게를 추가하고, 불가능할 때는 0으로 채우면 된다.

 

#include <iostream>
#include <vector>
#include <deque>

using namespace std;

int solution(int bridge_length, int weight, vector<int> truck_weights)
{
    int answer = 0;
    int nTrucks = truck_weights.size(), nPassed = 0, nWeight = 0;
    deque<int> trucks(truck_weights.begin(), truck_weights.end()), bridge(bridge_length, 0);

    while (nPassed != nTrucks)
    {
        if (int elem = bridge.front())
            ++nPassed, nWeight -= elem;

        bridge.pop_front();

        if (trucks.empty())
        {
            ;
        }
        else if (nWeight + trucks.front() <= weight)
        {
            nWeight += trucks.front();
            bridge.emplace_back(trucks.front());
            trucks.pop_front();
        }
        else
        {
            bridge.emplace_back(0);
        }

        ++answer;
    }

    return answer;
}
profile

Make Unreal REAL.

@diesuki4

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그