알고리즘

백준 11441번 합 구하기 (JAVA)

박카스마시며코딩 2022. 2. 8. 14:15

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

 

11441번: 합 구하기

첫째 줄에 수의 개수 N이 주어진다. (1 ≤ N ≤ 100,000) 둘째 줄에는 A1, A2, ..., AN이 주어진다. (-1,000 ≤ Ai ≤ 1,000) 셋째 줄에는 구간의 개수 M이 주어진다. (1 ≤ M ≤ 100,000) 넷째 줄부터 M개의 줄에는

www.acmicpc.net

 

저는 해당 문제를 sum이라는 배열을 통해 이전까지의 요소들의 합을 구하였습니다.

출력은 해당 각 인덱스에 대한 sum의 차를 출력하여 해결하였습니다.

 

package BOJ.ETC;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_11441 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine()," ");
        Function<String,Integer> stoi = Integer::parseInt;
        int n = stoi.apply(st.nextToken());
        int[] input = new int[n+1];
        int[] sum = new int[n+1];
        int temp = 0;
        st = new StringTokenizer(br.readLine()," ");
        for(int i = 1 ; i <= n ; i++){
            input[i] = stoi.apply(st.nextToken());
            temp += input[i];
            sum[i] = temp;
        }
        st = new StringTokenizer(br.readLine()," ");
        int m = stoi.apply(st.nextToken());
        for(int i = 0 ; i < m ; i++){
            st = new StringTokenizer(br.readLine()," ");
            int a = stoi.apply(st.nextToken());
            int b = stoi.apply(st.nextToken());
            System.out.println(sum[b] - sum[a-1]);
        }
    }
}