알고리즘문제풀이/프로그래머스

[프로그래머스] 셔틀버스_Java

초보개발자.. 2022. 3. 27. 15:43

--문제--

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

--문제 접근--

처음 문제를 읽었을 때 문제를 이해하기가 어려웠지만, 문제를 이해하고 난 뒤에는 곰곰이 생각하여 문제방향을 정하여 풀었습니다.

문제는 9시부터 n회 t분 간격으로 m명의 승객을 태워 출발하는 셔틀버스가 있는데 이 버스를 어떻게 막차를 타고 회사에 도착할지 판단하는 문제입니다.

그리하여 생각한 문제풀이 방향은 n회 간격으로 버스가 출발할 때 n-1회 까지는 대기하고 있는 승객들을 모두 태워보내고 마지막 버스일 때 검사를 하면 됩니다.

마지막 버스를 검사할 때 버스자리가 여유롭다면 버스 도착시간에 맞추어 기다리면 되고 버스가 Full이라면 마지막 버스에 타는 마지막 승객보다 1분먼저 오면 된다고 생각하여 코드를 구현하였습니다.

--코드--

package Level3;

import java.util.PriorityQueue;

public class 셔틀버스 {
	public static void main(String[] args) {
		int n=2;
		int t=10;
		int m=2;
		String[] timetable= {"09:10", "09:09", "08:00"};
		System.out.println(solution(n,t,m,timetable));
	}

	private static String solution(int n, int t, int m, String[] timetable) {
		
		PriorityQueue<Integer> pq=new PriorityQueue<>();
		for(String time:timetable) {
			int timeIntValue=convertTimetoInt(time);
			pq.add(timeIntValue);
		}
		//마지막 버스제외 모든 버스를 돌려 최대한 크루들을 회사로 보내기
		for(int i=0;i<n-1;i++) {
			int curTime=540+i*t;
			for(int j=0;j<m;j++) {
				if(pq.peek()<=curTime)pq.poll();
			}
		}
		//마지막 버스에대해 판단하는 
		int curTime=540+(n-1)*t;
		int ans=0;
		int size=0;
		for(int i=0;i<m;i++) {
			if(!pq.isEmpty()&&pq.peek()<=curTime) {
				ans=Math.max(ans, pq.poll());
				size++;
			}
		}
		//만약 버스가 가득 찬상태라면 최대로 늦게오신 분보다 1분먼저 오면 된다고판단
		if(size==m)ans-=1;
		//만약 그렇지 않다면 그냥 버스가 오는 시간에 맞춰서 오면 된다고 판단.
		else {
			ans=curTime;
		}
		
		StringBuilder sb=new StringBuilder();
		int hour=ans/60;
		int min=ans%60;
		if(hour<=9) {
			sb.append("0");
			sb.append(Integer.toString(hour));
			sb.append(":");
		}else {
			sb.append(hour);
			sb.append(":");
		}
		if(min<=9) {
			sb.append("0");
			sb.append(Integer.toString(min));
		}else {
			sb.append(min);
		}
		return sb.toString();
	}
	//다음번엔 이 방법을 사용..
//	String tmp=String.format("%02d:%02d", hour,min);
	private static int convertTimetoInt(String time) {
		int hour=Integer.parseInt(time.substring(0,2));
		int min=Integer.parseInt(time.substring(3,5));
		return hour*60+min;
	}
}