[Silver I] 회의실 배정 - 1931
성능 요약
메모리: 165876 KB, 시간: 1136 ms
분류
그리디 알고리즘(greedy), 정렬(sorting)
문제 설명
한 개의 회의실이 있는데 이를 사용하고자 하는 N개의 회의에 대하여 회의실 사용표를 만들려고 한다. 각 회의 I에 대해 시작시간과 끝나는 시간이 주어져 있고, 각 회의가 겹치지 않게 하면서 회의실을 사용할 수 있는 회의의 최대 개수를 찾아보자. 단, 회의는 한번 시작하면 중간에 중단될 수 없으며 한 회의가 끝나는 것과 동시에 다음 회의가 시작될 수 있다. 회의의 시작시간과 끝나는 시간이 같을 수도 있다. 이 경우에는 시작하자마자 끝나는 것으로 생각하면 된다.
입력
첫째 줄에 회의의 수 N(1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N+1 줄까지 각 회의의 정보가 주어지는데 이것은 공백을 사이에 두고 회의의 시작시간과 끝나는 시간이 주어진다. 시작 시간과 끝나는 시간은 231-1보다 작거나 같은 자연수 또는 0이다.
출력
첫째 줄에 최대 사용할 수 있는 회의의 최대 개수를 출력한다.
풀이
시작 시간을 기준으로 정렬을 한다면 시작 시간이 빠르지만 늦게 끝나는 경우를 고려하지 못한다.
그러니까 끝나는 시간을 기준으로 정렬을 하는 것이 핵심이다.
먼저 끝나는 회의 순서대로 회의실을 배정하다보면, 결국 가능한 회의 시간대 중 빠른 것들을 순서대로 고를 수 있게 된다.
또 주의할 점은 정렬할 때 끝나는 시간이 같을 때는 시작한 시간이 빠른 순서대로 정렬되어야 한다는 점이다.
(1,2) (3,5) (5,5)가 있다면 실제로는 3개 모두 선택 가능하지만, 정렬이 제대로 이루어지지 않았을 때에는 2개만 선택 가능한 것처럼 보일 수 있다.
시작과 동시에 끝나는 회의가 존재할 수 있기 때문에 이 조건도 고려해주어야 한다.
코드
package BOJ.Silver.s1;
import java.util.Arrays;
import java.util.Scanner;
class Meeting implements Comparable<Meeting> {
int start;
int end;
public Meeting(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public int compareTo(Meeting o) {
if (this.end == o.end)
return this.start - o.start;
return this.end - o.end;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return start + " " + end;
}
}
public class BOJ_1931_회의실배정 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
Meeting[] arr = new Meeting[N];
for (int i = 0; i < N; i++)
arr[i] = new Meeting(sc.nextInt(), sc.nextInt());
Arrays.sort(arr);
int end = 0;
int cnt = 0;
for (int i = 0; i < N; i++) {
if (arr[i].start >= end) {
cnt++;
end = arr[i].end;
}
}
System.out.println(cnt);
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 17281 - ⚾ (자바 Java) (1) | 2022.10.13 |
---|---|
[백준] 17136 - 색종이 붙이기 (자바 Java) (0) | 2022.10.13 |
[백준] 2206 - 벽 부수고 이동하기 (자바 Java) (0) | 2022.10.07 |
[백준] 16235 - 나무 재테크 (자바 Java) (1) | 2022.10.07 |
[백준] 17135 - 캐슬 디펜스 (자바 Java) (0) | 2022.10.06 |