2022 KAKAO BLIND RECRUITMENT
문제가 길다
간단히 하면
fees라는 배열에 기본시간, 기본요금, 단위시간, 단위요금이 int로 주어지고
records라는 배열에 입력된 시간, 차량 번호, 입차/출차 가 string으로 주어진다
이를 통해서 차량의 총 누적 시간에 따른 주차요금을 계산하여 배열로 반환하면 되는 문제
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <numeric>
using namespace std;
int Calculate(int bT, int bF, int pT, int pTF, int tT)
{
int fee = 0;
//요금계산
if (tT <= bT) //기본시간 이하
fee += bF;
else if (tT > bT) //기본시간 초과
{
fee += bF;
tT -= bT;
fee += tT / pT * pTF;
if (tT % pT > 0)
fee += pTF;
}
return fee;
}
vector<int> solution(vector<int> fees, vector<string> records)
{
map<int, pair<string, int>> m;
//carNum, time, fee
map<int, pair<int,bool>> car;
//carNum, 누적 시간 / in/out
int basicTime = fees[0];
int basicFee = fees[1];
int perTime = fees[2];
int perTimeFee = fees[3];
for (int i = 0; i < records.size(); i++)
{
string time = records[i].substr(0, 5);
int carNum = stoi(records[i].substr(6, 4));
bool in = records[i].substr(11) == "IN" ? true : false ;
int totalTime = 0;
int fee = 0;
if (in == true) //입차
{
if(m[carNum].second == 0)
m[carNum] = make_pair(time, 0);
car[carNum].second = true;
}
else if( in == false) //출차
{
car[carNum].second = false;
int inHour = stoi(m[carNum].first.substr(0, 2));
int inMin = stoi(m[carNum].first.substr(3, 2));
int outHour = stoi(records[i].substr(0, 2));
int outMin = stoi(records[i].substr(3, 2));
totalTime += (outHour - inHour) * 60; //시간 계산
totalTime += outMin - inMin; // 분 계산
car[carNum].first += totalTime;
}
}
for (auto i : car)
{
if (i.second.second == true) //출차기록 없음
{
int inHour = stoi(m[i.first].first.substr(0, 2));
int inMin = stoi(m[i.first].first.substr(3, 2));
int outHour = 23;
int outMin = 59;
car[i.first].first += (outHour - inHour) * 60; //시간 계산
car[i.first].first += outMin - inMin; // 분 계산
}
m[i.first].second = Calculate(basicTime, basicFee, perTime, perTimeFee, car[i.first].first);
}
vector<int> answer;
for (auto i : m)
{
answer.push_back(i.second.second);
}
return answer;
}
주의할 점은 총 누적 시간을 계산해야하므로 주차 요금을 출차 할 때 계산해버리면 안된다는 것이다
기본요금과 단위요금이 다르기 때문에
총 누적 시간을 기억해둔 뒤에 마지막에 한 번에 계산해야했다
차량 번호를 key로 사용하는 map 2가지를 선언했다
map<int, pair<string, int>> m;
-> 차량번호(int), 입/출차 시간(string), 요금(int)
map<int, pair<int,bool>> car;
-> 차량번호(int), 총 누적시간(int), 입/출차(bool)
string형식으로 들어오는 시간은 substr()과 stoi를 사용하여 문자열을 내 기준대로 자르고, int로 바꾸어서 사용했다
입차 시에는 bool을 true로, 출차 시에는 false로 해주었다
출차 시에는 총 누적시간을 분 단위로 모두 변환하여 map에 저장해주었다
모든 저장이 끝나면
for문을 돌려서 총 가격을 계산해주고, 입차기록만 남아있고 출차기록이 없을 경우의 예외처리도 해주었다
마지막으로 해당 요금들을 벡터에 저장하여 리턴해주었다
map은 자동으로 오름차순 정렬이 되므로 따로 정렬을 해 줄 필요는 없다
'> 코딩테스트' 카테고리의 다른 글
[프로그래머스] 의상 C++ (0) | 2024.01.23 |
---|---|
[프로그래머스] 디펜스 게임 C++ (0) | 2023.12.26 |
[백준] 24511 queuestack (C++) (0) | 2023.11.14 |
[백준] 28279 덱2 (C++) (2) | 2023.11.08 |
[백준] 10816 숫자카드2 (C++) (1) | 2023.10.31 |