주차 요금 계산(25분)

myeongrangcoding·2023년 11월 20일

프로그래머스

목록 보기
31/65

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

구현 아이디어 3분 구현 22분

풀이

차량 별 누적 주차 시간을 구하고 요금을 리턴하는 문제.

  • IN으로 끝날 경우 23:59까지 주차했다는 뜻이기 때문에 한번 더 검사해서 누적 시간을 더해줬다.
#include <string>
#include <vector>
#include <sstream>
#include <map>

using namespace std;

struct Data
{
    // 입차 시간.
    int in_car = -1;
    // 누적 주차 시간.
    int acc_car = 0;
};

// 문자열을 int형으로 바꿔줌.
int change(const string& s)
{
    int h = (s[0] - '0') * 10 + (s[1] - '0');
    int m = (s[3] - '0') * 10 + (s[4] - '0');
    
    return h * 60 + m;
}

int cal_acc(int in, int out)
{
    int acc = out - in;
    
    return acc;
}

vector<int> solution(vector<int> fees, vector<string> records) {
    vector<int> answer;
    
    map<string, Data> datas;
    for(int i = 0; i < records.size(); ++i)
    {
        stringstream ss(records[i]);
        string a, b, c;
        ss >> a >> b >> c;
        
        int time = change(a);
        
        if(c == "IN")
        {
            Data& data  = datas[b];
            data.in_car = time;
        }
        else if(c == "OUT")
        {
            Data& data = datas[b];
            
            // 누적.
            int acc = cal_acc(data.in_car, time);
            data.acc_car += acc;
            data.in_car = -1;
        }
    }
    
    // datas를 돌면서 in_car가 -1이 아닌 경우는 23:59까지 주차한 경우.
    for(auto& it : datas)
    {
        if(it.second.in_car != -1)
        {
            int acc = cal_acc(it.second.in_car, change("23:59"));
            it.second.acc_car += acc;
        }
    }
    
    // 디버깅.
    //for(auto it : datas)
        //printf("%s, %d\n", it.first.c_str(), it.second.acc_car);
    
    // 주차 요금 계산.
    // 기본 요금 + [(누적 시간 - 기본 시간)/단위 시간]*단위 요금;
    for(auto it : datas)
    {
        int result = fees[1];
        int acc = it.second.acc_car - fees[0];
        
        if(acc <= 0)
        {
            answer.push_back(result);
            continue;
        }
        else
        {
            result = result + ((acc + fees[2] - 1) / fees[2]) * fees[3]; 
            answer.push_back(result);
        }
    }
    
    return answer;
}
profile
명랑코딩!

0개의 댓글