쉬운 프로그래밍

[알고리즘] 백준 1931 회의실 배정 - JAVA 본문

알고리즘/그리디

[알고리즘] 백준 1931 회의실 배정 - JAVA

쉬운형 2021. 2. 19. 16:57

www.acmicpc.net/problem/1931

 

1931번: 회의실 배정

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

www.acmicpc.net

 

희의 종료시간이 빠른 순으로 정렬하고 회의시간이 겹치지 않는 경우를 카운팅 하면 되는 문제다.

 

이해가 가지 않으면 st-lab.tistory.com/145의 그림을 참고하면 쉽게 풀 수 있을 것이다.

 

코드 설명은 주석으로 달았다.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class BOJ_1931 {
    static int n;
    static int count = 0;
    static List<Meeting> list;

    public static void main(String[] args) throws IOException {

        //input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = br.readLine();
        n = Integer.parseInt(s);
        list = new ArrayList<Meeting>();

        for (int i = 0; i < n; i++) {
            s = br.readLine();
            StringTokenizer st = new StringTokenizer(s, " ");
            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());
            list.add(new Meeting(start, end));
        }
        // input end

        // list 정렬시에 만약 종료시간이 똑같다면
        // 시작시간이 빠른 순으로 정렬해야한다.
        Collections.sort(list);

        int prevEndTime = 0;

        // 초기값 0으로 잡아두고 회의시간이 겹치지 않으면
        // 즉 이전 끝난 시간보다 현재 시작 시간이 늦거나 같으면 카운팅
        for (int i = 0; i < n; i++) {
            if (prevEndTime <= list.get(i).start) {
                count++;
                prevEndTime = list.get(i).end;
            }
        }

        System.out.println(count);
    }

    static 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 m) {
            if (this.end < m.end)
                return -1;
            else if (this.end > m.end)
                return 1;
            else
                if (this.start < m.start)
                    return -1;
                else if (this.start > m.start)
                    return 1;
                else
                    return 0;
        }
    }

}

 

Comments