안녕하세요! 테크지니어22입니다.
오늘은 프로그래머스 알고리즘 주차 요금 계산 을 풀어보도록 하겠습니다.
https://school.programmers.co.kr/learn/courses/30/lessons/92341
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
[문제 접근]
문자열을 다루는 능력과 구현력을 요구하는 문제입니다. c++에서는 split함수가 제공되지 않기 때문에 직접 구현을 해주었고, unordered_map과 map을 이용하여 문제에 접근했습니다. 유의해야할 점은 00:00도 존재하기 때문에 Out을 할 때 0이 아니라 -1로 변경해주어야 합니다.
[풀이 전략]
1. 해쉬맵을 이용하여 In이면 시각을 분으로 나타낸 값을 저장하면 Out이면 -1으로 초기화합니다.
2. 맵을 이용하여 누적 시간을 저장한다.
3. 이 맵을 이용하여 누적 요금을 계산한다.
[코드]
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
using namespace std;
unordered_map<string,int> um ;
map<string,int> m ;
vector<string> split(string& s, string sep) {
int pos = 0 ;
vector<string> v ;
while(pos < s.size()){
int nxt_pos = s.find(sep,pos) ;
if( nxt_pos == -1) nxt_pos = s.size();
if(nxt_pos - pos > 0) { // 같으면 사실 넣을 문자열이 없기 때문
string tmp = s.substr(pos,nxt_pos-pos);
v.push_back(tmp);
}
pos = nxt_pos+sep.size() ;
}
return v ;
}
int convert_min(string time){
auto time_tmp = split(time, ":");
return (stoi(time_tmp[0])*60 + stoi(time_tmp[1]));
}
vector<int> solution(vector<int> fees, vector<string> records) {
vector<int> answer;
for(string record: records){
auto tmp = split(record, " ");
int mins = convert_min(tmp[0]);
if(tmp[2] == "IN") {
um[tmp[1]] = mins;
} else {
m[tmp[1]] += convert_min(tmp[0])- um[tmp[1]] ;
um[tmp[1]] = -1 ; // 00:00 때문에 0으로 하면 안됨.
}
}
for(auto e : um){
if(e.second !=-1){
m[e.first] += convert_min("23:59") - e.second ;
}
}
//요금 계산
for(auto e: m) {
if(e.second <= fees[0]) {
answer.push_back(fees[1]);
}
else {
int tmpsum = fees[1];
if((e.second - fees[0]) % fees[2] == 0) {
tmpsum += (e.second - fees[0]) / fees[2] * fees[3];
} else {
tmpsum += ((e.second - fees[0]) / fees[2]+1) * fees[3];
}
answer.push_back(tmpsum);
}
}
return answer;
}
[배울 점]
- split 함수 자동으로 구현이 될때까지 연습하기.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/C++] 알고리즘 - 괄호 변환 (0) | 2024.05.26 |
---|---|
[프로그래머스/C++] 알고리즘 - 메뉴 리뉴얼 (0) | 2024.05.25 |
[프로그래머스/C++] 알고리즘 - 양궁대회 (0) | 2024.05.23 |
[프로그래머스/C++] 알고리즘 - 도넛과 막대 그래프 (0) | 2024.05.16 |
[프로그래머스/C++] 알고리즘 - 주사위 고르기 (0) | 2024.05.12 |