Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-11659번/Java] 구간 합 구하기 4 본문

Algorithm

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

1984 2022. 11. 14. 22:53

* 누적된 합을 배열에 저장해서 풀었다.

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

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		String str = br.readLine();

		int N = Integer.parseInt(str.split(" ")[0]);
		int M = Integer.parseInt(str.split(" ")[1]);

		String numbers = br.readLine();
		StringTokenizer stk = new StringTokenizer(numbers, " ");

		int[] arr = new int[N];
		int sum = 0;
		int i = 0;
		while (stk.hasMoreElements()) {
			int num = Integer.parseInt(stk.nextToken());
			sum += num;
			arr[i] = sum;
			i++;
		}

		for (int j = 0; j < M; j++) {
			str = br.readLine();
			int a = Integer.parseInt(str.split(" ")[0]);
			int b = Integer.parseInt(str.split(" ")[1]);

			if (a >= 2) {
				bw.write(arr[b - 1] - arr[a - 2] + "\n");
			} else {
				bw.write(arr[b - 1] + "\n");
			}
		}

		bw.flush();

	}

}
728x90

'Algorithm' 카테고리의 다른 글

[백준-10814번] 나이순 정렬  (0) 2022.11.15
[백준-2559번/Java] 수열  (0) 2022.11.15
[백준-1676번/Java] 팩토리얼 0의 개수  (0) 2022.11.14
[백준-2798번/Java] 블랙잭  (0) 2022.11.14
[백준-18258번/Java] 큐 2  (0) 2022.11.14
Comments