Study/Coding Test

[2018 1차 KAKAO] 셔틀버스

_gayeon 2021. 10. 8. 22:47

https://programmers.co.kr/learn/courses/30/lessons/17678#

 

코딩테스트 연습 - [1차] 셔틀버스

10 60 45 ["23:59","23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59"] "18:00"

programmers.co.kr

 

SOL)

복잡하게 생각해서 풀이가 어려웠다.

단순히 두가지 경우의 수만 생각하자.

1. 마지막 셔틀에 자리가 있는 경우

2. 마지막 셔틀에 자리가 없는 경우

 

1번의 경우에는 마지막 셔틀이 오는 시간에 타면 되고

2번의 경우에는 마지막으로 탄 크루보다 1분 빠르게 탄다.

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int timeToInt(string time){
    int h = stoi(time.substr(0,2));
    int m = stoi(time.substr(3,2));
    
    return h*60 +m;
}

string timeToString(int time){
    int h = time/60;
    int m = time%60;
    
    string result = "";
    
    if(h<10) result+= '0';
    result+=to_string(h);
    result+= ':';
    if(m<10) result+='0';
    result+=to_string(m);
    
    return result;
}
string solution(int n, int t, int m, vector<string> timetable) {
    string answer = "";
    vector<int> crewTimeTable;

    //timetable 정렬
    sort(timetable.begin(), timetable.end());
    for(int i=0; i<timetable.size(); i++){
        crewTimeTable.push_back(timeToInt(timetable[i]));
    }
    
    int shuttle_time = timeToInt("09:00");
    int crewPtr = 0;
    for(int i=1; i<=n; i++, shuttle_time += t){
        int cnt= 0;
        for(int j=crewPtr; j<crewTimeTable.size(); j++){
            if(crewTimeTable[j] <= shuttle_time){ //셔틀에 타는경우
                cnt++;
                crewPtr++;
                if(cnt == m) break;
            }
        }
        
        if(i==n){ // 마지막 셔틀
            if(cnt == m){ //자리가 없는 경우
                answer = timeToString(crewTimeTable[crewPtr-1]-1);
            }
            else{ // 자리가 있는 경우
                answer = timeToString(shuttle_time);
            }
        }
    }

    return answer;
}