본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] 호텔 대실

728x90
반응형


🔗 문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/155651

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


반응형
728x90

👩‍💻 코드

#include <string>
#include <vector>
#include <utility>
#include <algorithm>
#include <queue>
#include <iostream>

using namespace std;

int timeToint(string time){
    int hours = stoi(time.substr(0, 2));
    int minutes = stoi(time.substr(3, 2));

    return hours * 60 + minutes;
}

int solution(vector<vector<string>> book_time) {
    vector<pair<int, int>> times;
    priority_queue<int, vector<int>, greater<int>> rooms;
    
    for (auto& bt : book_time) {
        int start = timeToint(bt[0]);
        int end = timeToint(bt[1]) + 10;
        times.push_back({start, end});
    }
    
    sort(times.begin(), times.end());
    
    for (auto& time : times) {
        int start = time.first;
        int end = time.second;

        if (!rooms.empty() && rooms.top() <= start) {
            rooms.pop();
        }

        rooms.push(end);
    }
    
    return rooms.size();
}

📝 풀이

체크 아웃 시간을 분으로 계산하여 예약을 관리합니다.

예약 시간들을 체크인과 체크아웃 시간 쌍으로 저장 후 체크인 시간을 기준으로 정렬합니다.

 

효율적으로 비어있는 방을 찾기 위해 우선 순위 큐를 사용하여 추적합니다.

비어 있는 방이 있다면 기존의 방을 할당하고 그렇지 않으면 새로운 방을 할당합니다.

 

최종적으로 남아있는 방의 갯수를 return 합니다.

 

728x90
반응형