Algorithm/Baekjoon

[Baekjoon 백준] 11659 구간 합 구하기 4 - Java

뭐든 해보기 2023. 1. 27. 18:00

문제) 수 N개가 주어졌을 때, i번째 수부터 j번째 수까지 합을 구하는 프로그램을 작성하시오.

 

입력) 첫째 줄에 수의 개수 N과 합을 구해야 하는 횟수 M이 주어진다. 둘째 줄에는 N개의 수가 주어진다. 수는 1,000보다 작거나 같은 자연수이다. 셋째 줄부터 M개의 줄에는 합을 구해야 하는 구간 i와 j가 주어진다.

 

출력) 총 M개의 줄에 입력으로 주어진 i번째 수부터 j번째 수까지 합을 출력한다.

 

제한)

  • 1 ≤ N ≤ 100,000
  • 1 ≤ M ≤ 100,000
  • 1 ≤ i ≤ j ≤ N

1. 사용할 변수 선언

2. 구간 합 배열 선언

3. 입력 된 값으로부터 구간 합 계산

4. 합 출력

 

public static void main(String[] args) throws IOException {
		//System.setIn(new FileInputStream("src/baekjoon/code11659"));
		Scanner sc = new Scanner(System.in);
  
		int N; //제시 된 수 개수
		int T; //계산할 정렬 개수
		N = sc.nextInt();
		T = sc.nextInt();
 
		int[] S = new int[N+1]; // 구간 합 배열
 
 		//구간 합 계산
		for (int i = 1; i <= N; i++) {	
			S[i] = S[i-1] + sc.nextInt();
		}
        
		//합 출력
		for(int t=0; t<T; t++) {
			int i = sc.nextInt();
			int j = sc.nextInt();
			System.out.println(S[j] - S[i-1]);
		} 
	}

 

위 코드로는 시간초과가 났다.

 

public static void main(String[] args) throws FileNotFoundException {
		//System.setIn(new FileInputStream("src/baekjoon/code11659"));
		Scanner sc = new Scanner(System.in);
  
		int N; //계산할 수 개수
		int T; //계산할 정렬 개수
		N = sc.nextInt();
		T = sc.nextInt();

		int[] A = new int[N]; // 수 배열
		int[] S = new int[N]; // 구간 합 배열
		int sum = 0; // 합계 
 		//입력된 수 저장
		for (int i = 0; i < N; i++) { 
			A[i] = sc.nextInt();
		}
		
		//구간 합 계산
		S[0] = A[0];
		for(int i=1; i<N; i++) {
			S[i] = A[i] + S[i-1];
		}
 		//케이스 별 나눠서 처리
		for(int i=0; i<T; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			
			if(a == 1) {
				System.out.println(S[b-1]);
			}
			else if(a == b) {
				System.out.println(A[b-1]);
			}
			else {
				System.out.println(S[b-1] -  S[a-2]);
			} 
		} 
	}

 

얘는 시간초과 안났다.

그래서 첫번째 코드를 BufferedReader로 바꿔서 제출해봤다.

 

public static void main(String[] args) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
		
		int N; //계산할 수 개수
		int T; //계산할 정렬 개수
		N =Integer.parseInt(stringTokenizer.nextToken());
		T = Integer.parseInt(stringTokenizer.nextToken());
 
		int[] S = new int[N+1]; // 구간 합 배열

		stringTokenizer = new StringTokenizer(bufferedReader.readLine());
		//구간 합 계산
		for (int i = 1; i <= N; i++) {
			S[i] = S[i-1] + Integer.parseInt(stringTokenizer.nextToken());
		}
		//합 출력
		for(int t=0; t<T; t++) {
			stringTokenizer = new StringTokenizer(bufferedReader.readLine());
			int i = Integer.parseInt(stringTokenizer.nextToken());
			int j = Integer.parseInt(stringTokenizer.nextToken());
			System.out.println(S[j] - S[i-1]);
		} 
	}

 

통과됐다.

확실히 두 번째 코드보다 메모리 및 실행시간 차이가 많이났다.

두 번째 코드 : 255824KB/2560ms

세 번째 코드 : 58780KB/1412ms

 

BufferedReader가 확실히 처리 속도가 빠르다.