백준 11659 - 구간 합 구하기4
Updated:
Java
11659 번 - 구간 합 구하기4
문제
접근 방법
누적 합을 사용하여 해결하였다.
코드
import java.util.*;
import java.io.*;
public class Main {
	static int n, m, result;
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    	StringTokenizer stk = new StringTokenizer(br.readLine());
    	n = stoi(stk.nextToken());
    	m = stoi(stk.nextToken());
    	int[] arr = new int[n + 1];	// 누적 합
    	stk = new StringTokenizer(br.readLine());
    	for(int i = 1; i <= n; i++)
    		arr[i] = arr[i - 1] + stoi(stk.nextToken());
    	int s,e;
    	while(m-- != 0) {
    		stk = new StringTokenizer(br.readLine());
    		s = stoi(stk.nextToken()) - 1;
    		e = stoi(stk.nextToken());
    		System.out.println(arr[e] - arr[s]);
    	}
    	br.close();
	}
	static int stoi(String str) {
    	return Integer.parseInt(str);
    }
}
