본문 바로가기
problem solving/ps java

[ps java] BOJ 11660 구간 합 구하기 5 해설

by 클레어몬트 2025. 4. 21.

2차원 배열의 누적 합을 공부할 수 있는 대표 예제 [실버1]

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

 

 

 

문제

N×N개의 수가 N×N 크기의 표에 채워져 있다. (x1, y1)부터 (x2, y2)까지 합을 구하는 프로그램을 작성하시오. (x, y)는 x행 y열을 의미한다.

예를 들어, N = 4이고, 표가 아래와 같이 채워져 있는 경우를 살펴보자.

여기서 (2, 2)부터 (3, 4)까지 합을 구하면 3+4+5+4+5+6 = 27이고, (4, 4)부터 (4, 4)까지 합을 구하면 7이다.

표에 채워져 있는 수와 합을 구하는 연산이 주어졌을 때, 이를 처리하는 프로그램을 작성하시오.

입력

첫째 줄에 표의 크기 N과 합을 구해야 하는 횟수 M이 주어진다. (1 ≤ N ≤ 1024, 1 ≤ M ≤ 100,000) 둘째 줄부터 N개의 줄에는 표에 채워져 있는 수가 1행부터 차례대로 주어진다. 다음 M개의 줄에는 네 개의 정수 x1, y1, x2, y2 가 주어지며, (x1, y1)부터 (x2, y2)의 합을 구해 출력해야 한다. 표에 채워져 있는 수는 1,000보다 작거나 같은 자연수이다. (x1 ≤ x2, y1 ≤ y2)

출력

총 M줄에 걸쳐 (x1, y1)부터 (x2, y2)까지 합을 구해 출력한다.

예제 입력 1

4 3
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
2 2 3 4
3 4 3 4
1 1 4 4

예제 출력 1

27
6
64

예제 입력 2

2 4
1 2
3 4
1 1 1 1
1 2 1 2
2 1 2 1
2 2 2 2

예제 출력 2

1
2
3
4

 

 

 

 

(답안 코드)

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

public class Main {
    private static int[][] cumSum;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());

        cumSum = new int[N + 1][N + 1]; // (1, 1)부터 시작하는 누적 합 배열
        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                // 가로, 세로는 더하고 대각선은 빼기(중복)
                cumSum[i + 1][j + 1] = cumSum[i][j + 1] + cumSum[i + 1][j] - cumSum[i][j] + Integer.parseInt(st.nextToken());
            }
        }

        for (int i = 0; i < N + 1; i++) {
            for (int j = 0; j < N + 1; j++) {
                System.out.print(cumSum[i][j] + " ");
            }
            System.out.println();
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int x1 = Integer.parseInt(st.nextToken());
            int y1 = Integer.parseInt(st.nextToken());
            int x2 = Integer.parseInt(st.nextToken());
            int y2 = Integer.parseInt(st.nextToken());

            sb.append(getSum(x1 - 1, y1 - 1, x2 - 1, y2 - 1)).append("\n");
        }

        System.out.println(sb);

        br.close();
    }

    private static int getSum(int x1, int y1, int x2, int y2) {
        // 가로 세로 빼고 대각선은 더하기(중복)
        return cumSum[x2 + 1][y2 + 1] + cumSum[x1][y1] - cumSum[x2 + 1][y1] - cumSum[x1][y2 + 1];
    }
}

 

(2, 2) ~ (3, 4) 에 대한 그림

이런 원리로 3 + 4 + 5 + 4 + 5 + 6 = 27 이 나오는 것이다!

 

초록색 동그라미: 선택한 기준점

파란색 네모: 더하는 부분

빨간색 네모: 빼는 부분

 

 

 

 

 

#SK, #SKALA, #SKALA1기