문제풀이/알고리즘 문제 풀이
[ 프로그래머스 ] 주차 요금 계산 (C++) - 구현
RealTone
2024. 4. 5. 15:48
728x90
🔗 문제 링크
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
💡 문제 풀이 및 해석
- 각 차량번호마다 key를 부여한다. 이 때, map 자체에서 key에 대해서 오름차순으로 정렬한다.
- 이 key에 시간을 누적한다.
- 모든 시간이 누적되었을 때, 아직 입차되어 있는 상태인 자동차만 따로 시간을 더해준다.
- 시간에 대한 주차요금을 정산하여 answer에 넣어준다.
⭐️ 정답 코드 및 설명
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
vector<int> solution(vector<int> fees, vector<string> records) {
vector<int> answer;
int basicTime=fees[0], basicFee=fees[1], unitTime=fees[2],unitFee=fees[3];
map<string,pair<int,bool>> info; // carNum, time, state
map<string,int> myTime; // carNum, useTime
for(string record : records){
int time = stoi(record.substr(0,2))*60+stoi(record.substr(3,2));
string carNum=record.substr(6,4);
string type=record.substr(11,3);
if(type=="IN") info[carNum]={time,true};
if(type=="OUT"){
myTime[carNum]+=time-info[carNum].first;
info[carNum].second=false;
// cout<<carNum<<" "<<myTime[carNum]<<endl;
}
}
for(string record : records){
string carNum=record.substr(6,4);
if(info[carNum].second){
myTime[carNum]+=1439-info[carNum].first;
info[carNum].second=false;
// cout<<carNum<<" "<<myTime[carNum]<<endl;
}
}
for(auto timeInfo : myTime){
int fee = basicFee;
if(timeInfo.second - basicTime>0){
fee+=((timeInfo.second-basicTime)/unitTime) * unitFee;
if((timeInfo.second-basicTime)%unitTime>0) fee+=unitFee;
}
answer.push_back(fee);
}
return answer;
}
🤔 문제 후기
문제 자체가 푸는데 어려운건 아니였다. 처음에 substr
를 사용할 때, 찾는 위치가 index를 넘어가면 자동적으로 마지막에서 멈추는 것을 처음 알았다. 그 덕에 더 쉽게 풀 수 있는 문제 였던 것 같다. 그 점을 제외하고는 다른 구현 문제와 별 다를게 없었다.
728x90