Post

[백준] 11441번 - 합 구하기 [Java][C++]

[백준] 11441번 - 합 구하기 [Java][C++]

문제 링크


1. 문제 풀이

$N$ 개의 수에 대해 $M$ 개의 각 구간의 합을 구해야 하는 문제로 매번 주어진 구간의 합을 반복문으로 구하면 $O(NM)$ 의 시간복잡도로 동작한다. 반복되는 구간의 합을 빠르게 구할 수 있는 누적합을 활용했다.


2. 코드

1. 누적합 [Java]

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
29
30
31
32
33
34
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));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st;

        int N = Integer.parseInt(br.readLine());

        int[] arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        int[] pSum = new int[1 + N];
        for (int i = 1; i <= N; i++) {
            pSum[i] = pSum[i - 1] + arr[i - 1];
        }

        int M = Integer.parseInt(br.readLine());
        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int start = Integer.parseInt(st.nextToken());
            int end = Integer.parseInt(st.nextToken());

            sb.append(pSum[end] - pSum[start - 1]).append("\n");
        }

        System.out.println(sb);
    }
}

2. 누적합 [C++]

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;

    vector<int> psum(1 + n);
    for (int i = 1; i <= n; i++) {
        psum[i] = psum[i - 1] + v[i - 1];
    }

    int m;
    cin >> m;

    for (int i = 0; i < m; i++) {
        int s, e;
        cin >> s >> e;
        cout << psum[e] - psum[s - 1] << '\n';
    }
}

3. 풀이 정보

1. 누적합 [Java]

언어시간메모리코드 길이
Java 11572 ms58304 KB1023 B

2. 누적합 [C++]

언어시간메모리코드 길이
C++ 1736 ms2804 KB465 B

This post is licensed under CC BY 4.0 by the author.