[백준][Java] 15486 - 퇴사 2

박현아·2024년 10월 29일
0

백준

목록 보기
2/4

👩‍💻 문제

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

🙋‍♀️ 답변

  • Scanner 사용 (시간 2752ms)
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		int N = sc.nextInt();
		int[] T = new int[N+1];
		int[] P = new int[N+1];
		int[] D = new int[N+2];
		
		for (int i =1; i<=N; i++) {
			T[i]= sc.nextInt();
			P[i] = sc.nextInt();
		}
		
		for (int i=N; i>0; i--) {
			if (i + T[i] <= N+1) {
				D[i] = Math.max(D[i+1], P[i] + D[i +T[i]]);
			} else {
				D[i] = D[i+1];
			}
		}
		
		System.out.println(D[1]);
	}

}
  • BufferedReader 사용 (시간 696ms)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		int[] T = new int[N+1];
		int[] P = new int[N+1];
		int[] D = new int[N+2];
		
		for (int i =1; i<=N; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			T[i]= Integer.parseInt(st.nextToken());
			P[i] = Integer.parseInt(st.nextToken());
		}
		
		for (int i=N; i>0; i--) {
			if (i + T[i] <= N+1) {
				D[i] = Math.max(D[i+1], P[i] + D[i +T[i]]);
			} else {
				D[i] = D[i+1];
			}
		}
		
		System.out.println(D[1]);
	}

}

🤔

백준 퇴사 문제처럼 Scanner를 썼더니 시간이 엄청 오래 걸려서 BufferedReader를 썼더니 빨라졌다. 퇴사 문제와 뭐가 다른가 했더니 퇴사 2는 N 범위가 무려 150만 !!!!
BufferedReader는 처음 써보는데 따로 정리해놔야겠다. 대용량 입력을 받을 때 성능이 Scanner 보다 좋다고 한다. (정리 완료!)
BufferedReader 빼고는 퇴사 문제와 똑같이 풀 수 있었다.

0개의 댓글