Post

[JAVA]백준 2003번 수들의 합 2

[JAVA]백준 2003번 수들의 합 2

📌문제 링크


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

Image

📌문제 설명


주어진 숫자 배열에서 연속된 부분 배열의 합이 M이 되는 경우의 수를 구하는 문제입니다. 해시맵을 이용하여 현재까지의 합을 저장하고, 이를 통해 효율적으로 경우의 수를 계산합니다.

📌코드


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
35
36
37
38
39
40
41
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static int N, M, answer = 0;
    static int[] arr = new int[10001];

    public static void main(String[] args) throws Exception {
        input(); // 입력을 받는 메서드 호출
        solve(); // 문제를 해결하는 메서드 호출
    }

    public static void input() throws Exception {
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken()); // 첫 번째 입력값을 N으로 설정
        M = Integer.parseInt(st.nextToken()); // 두 번째 입력값을 M으로 설정
        st = new StringTokenizer(br.readLine());
        for(int i = 1; i <= N; i++) {
            arr[i] = Integer.parseInt(st.nextToken()); // 배열에 입력값 추가
        }
        br.close(); // BufferedReader 닫기
    }

    public static void solve() {
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, 1); // 초기값 설정
        int currentSum = 0;

        for (int i = 1; i <= N; i++) {
            currentSum += arr[i];
            if (map.containsKey(currentSum - M)) {
                answer += map.get(currentSum - M);
            }
            map.put(currentSum, map.getOrDefault(currentSum, 0) + 1);
        }
        System.out.println(answer); // 결과 출력
    }
}
This post is licensed under CC BY 4.0 by the author.