Level 2. 주차 요금 계산
입차일 경우 차량 번호와 입차 시간을 기록하고, 출차일 경우 주차 시간을 계산해 더한 후 입차 시간을 초기화한다.
map의 키가 차량 번호이기 때문에 작은 순서대로 이미 정렬되어 있다.
입차 시간이 초기화되지 않은(-1) 차들은 출차 시간을 23:59로 하여 한 번 더 더해주어야 한다.
벡터에 원소를 추가할 때 메모리 재할당을 방지하기 위해 vector.reserve() 함수로 용량을 미리 지정했다.
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
struct Record
{
int time;
int carId;
bool isIn;
Record(string record)
{
time = stoi(record.substr(0, 2)) * 60 + stoi(record.substr(3, 2));
carId = stoi(record.substr(6, 4));
isIn = (record[11] == 'I');
}
};
vector<int> solution(vector<int> fees, vector<string> records)
{
int defaultTime = fees[0], defaultFee = fees[1];
float extraTime = fees[2], extraFee = fees[3];
auto calculateFee = [&](int totalTime) -> int
{
return defaultFee + max(0.F, ceil((totalTime - defaultTime) / extraTime)) * extraFee;
};
vector<int> answer;
map<int, int> inTime;
map<int, int> fee;
for (string record : records)
{
Record r(record);
if (r.isIn)
{
inTime[r.carId] = r.time;
}
else
{
fee[r.carId] += r.time - inTime[r.carId];
inTime[r.carId] = -1;
}
}
answer.reserve(fee.size());
for (auto& pr : inTime)
{
if (pr.second != -1)
fee[pr.first] += (1439 - pr.second);
answer.emplace_back(calculateFee(fee[pr.first]));
}
return answer;
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 2. 영어 끝말잇기 (0) | 2023.03.25 |
---|---|
Level 2. JadenCase 문자열 만들기 (0) | 2023.03.24 |
Level 2. 숫자 변환하기 (0) | 2023.03.22 |
Level 2. 튜플 (0) | 2023.03.21 |
Level 2. 오픈채팅방 (0) | 2023.03.20 |