본문 바로가기
알고리즘/백준

[BOJ 백준] 1931 - 회의실 배정, Java(자바)

by eungineer 2023. 3. 7.

문제

https://www.acmicpc.net/problem/1931

 

1931번: 회의실 배정

(1,4), (5,7), (8,11), (12,14) 를 이용할 수 있다.

www.acmicpc.net

풀이

그리디 + 정렬로 문제를 풀었다. 먼저 회의를 종료 시간이 가장 빠른 순서대로 정렬한다. 이때, 종료 시간이 같다면 시작 시간이 빠른 순서대로 정렬한다. current에 현재 시간을 표시하고, 배열을 돌면서 현재 시간이 회의 시작 시간보다 작거나 같다면 현재 시간을 회의 종료 시간으로 바꾸고 카운트를 늘린다.

코드

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String args[]) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(in.readLine());
        int[][] arr = new int[N][2];
        for (int i = 0; i < N; i++) {
            StringTokenizer st = new StringTokenizer(in.readLine());
            arr[i][0] = Integer.parseInt(st.nextToken());
            arr[i][1] = Integer.parseInt(st.nextToken());
        }
        Arrays.sort(arr, new Comparator<int[]>() {
           @Override
           public int compare(int[] o1, int[] o2) {
               return o1[1] == o2[1] ? o1[0] - o2[0] : o1[1] - o2[1];
           }
        });
        int current = 0, cnt = 0;
        for (int i = 0; i < N; i++) {
            if (arr[i][0] >= current) {
                cnt++;
                current = arr[i][1];
            }
        }
        System.out.println(cnt);
    }
}