알고리즘 ( C++ )/프로그래머스

[프로그래머스] [1차] 카카오 셔틀버스 c++

kwoss2341 2021. 1. 21. 16:04

 

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

 

기본적인 아이디어.

 

콘은 게으르기 때문에 셔틀버스 막차를 탄다.

콘이 안탔을 경우 막차의 남은 자리가 있는지 판단한다.

 

만약 막차에 자리가 남았다 -> 콘은 막차 도착시간에 맞춰서 판교역에 간다.

만약 막차에 자리가 가득찼다 -> 콘은 마지막으로 탄 크루보다 1분 일찍 가면 탈 수 있다.

 

 

세부적인 아이디어.

 

timetable을 파싱하여 시간을 분단위로 치환 후 정렬하여 구현한다.

 

 

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

using namespace std;

//https://programmers.co.kr/learn/courses/30/lessons/17678
string solution(int n, int t, int m, vector<string> timetable) {
    string answer = "";
    int ia;
    int s=timetable.size();
    vector <int> crew;
    
    for(int i=0; i<s; i++)
    {
        crew.push_back(stoi(timetable[i].substr(0,2))*60+stoi(timetable[i].substr(3,2)));
    }
    
    sort(crew.begin(), crew.end());
    
    
    vector <int> last;
    int sttime=9*60;
    int st=0;
    for(int i=0; i<n; i++)
    {
        
       
       for(int j=0; j<m; j++)
       {
          if(st>s-1) break; 
           
          if(crew[st]<=sttime)
          {
              if(i==n-1)
              {
                  last.push_back(crew[st]);
              }
              st++;
          }
          else
          {
              break;
          }
       }
       
       if(i==n-1)
       {
           if(last.size()<m)
           {
               ia=sttime;
           }
           else
           {
               ia=last[last.size()-1]-1;
           }
       }
       
       sttime+=t; 
    }
    
    if(ia/60<10)
    {
        answer="0"+to_string(ia/60);
    }
    else
    {
        answer=to_string(ia/60);
    }
    
    answer+=":";
    
    if(ia%60<10)
    {
        answer+="0"+to_string(ia%60);
    }
    else
    {
        answer+=to_string(ia%60);
    }
    
    return answer;
}

 

셔틀버스 실행시간