-
[JAVA]백준_1931_회의실 배정알고리즘/Greedy 2023. 7. 1. 11:53
문제: https://www.acmicpc.net/problem/1931
문제 유형: Greedy
코드:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Main { private static int count = 0; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); String input = ""; int [][] times = new int[N][2]; for(int i=0; i<N; i++){ StringTokenizer st = new StringTokenizer(br.readLine(), " "); times[i][0] = Integer.parseInt(st.nextToken()); times[i][1] = Integer.parseInt(st.nextToken()); } // 그리디를 활용한 풀이 Arrays.sort(times, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if(o1[1] == o2[1]){ return o1[0] - o2[0]; }else return o1[1] - o2[1]; } }); int count = 1; int end = times[0][1]; // 끝나는 시간이 빠른 것으로 정렬되어 있으니... for (int i = 1; i < N; i++) { if(end <= times[i][0]){ count++; end = times[i][1]; } } System.out.print(count); } }
결과:
배운점:
StringTokenizer 와 Comparator 의 override 를 사용하면 메모리와 시간적인 측면에서 큰 이점을 가져갈 수 있다는 것을 알게 되었다.
상위 코드들과 내 코드를 비교해 봤을 때 상위 코드들은 다 입력을 커스텀하여 시간을 단축하였다.
하지만 나는 코테볼 때 그렇게까진 안할 것같아서 나와의 차이를 비교해봤는데
StringTokenizer 와 Comparator가 그 차이였다.
맨 아래가 그냥 split 과 lamda 식을 활용했을 때의 메모리와 시간이고 둘을 활용하니 메모리와 시간이 반으로 줄어든 것을 확인하였다.
split과 lamda를 사용했던 코드:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class Main { private static int count = 0; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); String input = ""; int [][] times = new int[N][2]; for (int i = 0; i < N; i++) { input = br.readLine(); times[i][0] = Integer.parseInt(input.split(" ")[0]); times[i][1] = Integer.parseInt(input.split(" ")[1]); } // 그리디를 활용한 풀이 Arrays.sort(times,(o1,o2)->{ if(o1[1] == o2[1]){ return Integer.compare(o1[0],o2[0]); }else { return o1[1]-o2[1]; // 끝나는 시간으로 정렬하는 것. } }); // int count = 1; int end = times[0][1]; // 끝나는 시간이 빠른 것으로 정렬되어 있으니... for (int i = 1; i < N; i++) { if(end <= times[i][0]){ count++; end = times[i][1]; } } System.out.print(count); } }