본문 바로가기
Problem Solving

[c++][프로그래머스] 주차 요금 계산

by wadekang 2022. 1. 20.

프로그래머스 주차 요금 계산 [2022 KAKAO BLIND RECRUITMENT]
https://programmers.co.kr/learn/courses/30/lessons/92341
 

코딩테스트 연습 - 주차 요금 계산

[180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]

programmers.co.kr

 

문제 풀이

  • 먼저 각 차량 별로 주차 내역을 map에 담아줍니다. 그 결과는 다음 그림과 같습니다.

차량별 주차 내역

  • 그 다음 차량 주차 내역의 개수가 홀수라면 내역의 마지막에 "23:59"를 추가합니다. (출차된 내역이 없다면 23:59에 출차된 것으로 간주하기 때문)

0000 차량의 주차 내역에 "23:59" 추가

  • 현재 차량의 주차 내역 vector에는 IN, OUT, IN, OUT --- 의 순서로 담겨 있기 때문에 IN, OUT을 하나씩 짝지어서 주차한 시간을 계산(OUT time - IN time)하고, 그것을 모두 더해 총 주차시간을 구합니다. 
  • 총 주차시간이 기본 시간 이하면 기본 요금, 이상이면 기본 요금 + ⌈(총 주차시간 - 기본 시간) / 단위 시간⌉ * 단위 요금을 청구합니다.
  • 마지막으로 차량 번호가 작은 자동차부터 answer vector에 담아주어야 하는데, map을 사용하면 key 값을 기준으로 자동 정렬되기 때문에 map에 담긴 순서대로 answer vector에 담아주면 됩니다. 

코드

#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>

using namespace std;

int time_diff(string in, string out) {
    int h1 = stoi(in.substr(0, 2));
    int m1 = stoi(in.substr(3, 2));
    int h2 = stoi(out.substr(0, 2));
    int m2 = stoi(out.substr(3, 2));
    
    int diff = (h2-h1)*60 + (m2-m1);
    
    return diff;
}

vector<int> solution(vector<int> fees, vector<string> records) {
    vector<int> answer;
    map<string, vector<string>> m;
    
    stringstream ss;
    for(auto record: records) {
        ss.str(record);
        string time, number, status; ss >> time >> number >> status;
        
        m[number].push_back(time);
        ss.clear();
    }
    
    for(auto it: m) {
        if(it.second.size() & 1) // 주차 내역 홀수면 "23:59" 추가
            it.second.push_back("23:59");
        
        vector<string> info = it.second;
        int total = 0;
        for(int i=0; i<info.size()-1; i+=2) {
            total += time_diff(info[i], info[i+1]);
        }
        
        int price = fees[1];
        if(total > fees[0]) {
            price += ceil((total-fees[0]) / (double)fees[2]) * fees[3];
        }
        
        answer.push_back(price);
    }
    
    return answer;
}

실행 결과

 

댓글