주차 요금 계산

유승선 ·2022년 9월 15일
0

프로그래머스

목록 보기
25/48

풀만한 문제를 이것저것 찾아보다가 예전에 군대에서 풀어봤던 문제가 생각나서 다시 해봤다. 사지방에서 이 문제를 풀면서 뒤에서 탁구공들이 날라다니고 정담을 맞췄을때 좋아했던 기억이 났었다. 그때와 비교해서 실력이 많이 늘기도 했고 다시 문제를 풀었을때도 역시 쉽게 풀었다. 다만, 어떻게 하면 더 잘 풀 수 있을까에 대한 고민을 해보긴 했지만 처음 생각했던 방식 그대로 풀었다.

#include <string>
#include <vector>
#include <bits/stdc++.h>  
using namespace std;

int convert(string time){
    string HH = time.substr(0,2); 
    string MM = time.substr(3,2);  
    
    int int_HH = stoi(HH) * 60; 
    int int_MM = stoi(MM); 
    
    return int_HH + int_MM; 
}

int calculate(int number, vector<int>& fees){
    int base_time = fees[0], base_pay = fees[1], base_minute = fees[2], over_pay = fees[3]; 
    return number <= base_time ? base_pay : base_pay + ceil((double)(number - base_time) / base_minute) * over_pay; 
}

vector<int> solution(vector<int> fees, vector<string> records) {
    vector<int> answer;
    map<string,int> car_times; 
    map<string,vector<int>> in_out_times; 
    for(string& s : records){
        istringstream iss(s); 
        string time, car_num, command; 
        iss >> time >> car_num >> command; 
        if(command == "IN"){
            in_out_times[car_num].push_back(convert(time)); 
        }
        if(command == "OUT"){
            int total_time = convert(time) - in_out_times[car_num][0]; 
            car_times[car_num] += total_time; 
            in_out_times[car_num].pop_back(); 
        }
    }
    
    for(auto& it : in_out_times){
        if(!it.second.empty()){
            car_times[it.first] += (convert("23:59") - in_out_times[it.first][0]); 
        }
    }
    
    for(auto& it : car_times){
        answer.push_back(calculate(it.second,fees)); 
    }
    return answer;
}

특별한 방법은 없었고 istringstream 을 타입처럼 생각하고 iss 변수를 만드는게 오래 전에 해본 일이라 잘 기억이 안났다. 그래도 string 관련 문제를 풀때 이렇게 풀어주면 되게 좋을거 같다는 생각이 들었다. ceil() 로 계산 하는 과정이 좀 헷갈렸는데 너무 특이한 케이스라 일단 저렇게 풀 수 도있구나 하는 생각만 가졌다.

그 외는 그냥 문제를 읽고 내가 직감적으로 이렇게 풀면 되겠다 하는데로 적었는데 20분내로 빠르게 풀었던거같다. 실제 시험에서도 이렇게 쉬운 문제가 계속 나오면 좋겠다. 예전 풀이를 참고해보니 이것보다 더 복잡하게 풀었어서 침착함을 유지하는게 정말 중요할거같다.

배운점:
1. istringstream iss(s) 기억하자
2. 침착함 유지하기

profile
성장하는 사람

0개의 댓글