[알고리즘][X] 공주님의 정원

2024. 2. 26. 17:14알고리즘 풀이/Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;

public class Main {
	
	static StringBuilder sb = new StringBuilder();
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		int N = Integer.parseInt(br.readLine());
		int[] dayPerMonth = {0, 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		for (int i = 1; i < dayPerMonth.length; i++) {
			dayPerMonth[i] += dayPerMonth[i-1];
		}
		
		int[][] projects = new int[N][2];
		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			int startMonth = Integer.parseInt(st.nextToken());
			int startDay = Integer.parseInt(st.nextToken());
			int endMonth = Integer.parseInt(st.nextToken());
			int endDay = Integer.parseInt(st.nextToken());
			projects[i][0] = dayPerMonth[startMonth] + startDay;
			projects[i][1] = dayPerMonth[endMonth] + endDay - 1;
			
		}
		
		
		int startCondition = dayPerMonth[3] + 1;
		int endCondition = dayPerMonth[11] + 30;
		
		Arrays.sort(projects, new Comparator<int[]>() {

			@Override
			public int compare(int[] o1, int[] o2) {
				if (o1[0] != o2[0]) {
					return o1[0] - o2[0];
				} else {
					return o2[1] - o1[1];
				}
			}
			
		});
		
		int curEnd = startCondition - 1;
		int candidate = -1;
		int count = 0;
		for (int i = 0; i < N; i++) {
			int[] projectPeriod = projects[i];
			int projectStartDay = projectPeriod[0];
			int projectEndDay = projectPeriod[1];
			if (curEnd >= projectStartDay - 1) {
				if (candidate == -1) {
					candidate = i;
					count++;
				} else if (projects[candidate][1] < projectEndDay) {
					candidate = i;
				}
			} else {
				if (candidate == -1) {
					sb.append(0);
					break;
				}
				curEnd = projects[candidate][1];
				candidate = -1;
				i--;
			}
			
			if (i == N - 1) {
				curEnd = projects[candidate][1];
				if (curEnd < endCondition) {
					sb.append(0);
					break;
				}
			}
			if (curEnd >= endCondition) {
				sb.append(count);
				break;
			}
		}
		
		
		System.out.println(sb);
	}

}

나의 풀이

- 시작 조건 값은 포함되어야 하고 다른 끝점들은 포함되지 않아도 되는 걸 고려해야 풀리는 문제이다.

'알고리즘 풀이 > Java' 카테고리의 다른 글

[알고리즘] 최단경로  (0) 2024.02.27
[알고리즘] 낚시왕  (1) 2024.02.27
[알고리즘] 점심 식사시간  (0) 2024.02.25
[알고리즘] DP 테이블의 차원에 대한 꿀팁  (0) 2024.02.24
[알고리즘] ⚾  (0) 2024.02.23