백준 2167 2차원배열 합

정호윤·2023년 3월 16일

자바

목록 보기
35/46

백준문제링크

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

class Main{
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        int N= sc.nextInt();
        int M= sc.nextInt();
        int[][] arr = new int[N+1][M+1];
        // 2차원 배열을 입력받는다.
        for(int i=1;i<=N;i++){
            for(int j=1;j<=M;j++){
                arr[i][j]=sc.nextInt();
            }
        }
        // 합배열을 만든다.
        int[][] arr2 = new int[N+1][M+1];
        for(int i=1;i<=N;i++){
            for(int j=1;j<=M;j++){
                // 공식을 기억하자
                arr2[i][j]=arr2[i-1][j]+arr2[i][j-1]-arr2[i-1][j-1]+arr[i][j];
            }
        }
        int K = sc.nextInt();
        for(int i=0;i<K;i++){
            int x1 = sc.nextInt();
            int y1 = sc.nextInt();
            int x2 = sc.nextInt();
            int y2 = sc.nextInt();
            // 구간합을 구한다.공식을 기억하자
            int sol = arr2[x2][y2]-arr2[x1-1][y2]-arr2[x2][y1-1]+arr2[x1-1][y1-1];
            System.out.println(sol);
        }
    }
}

2차원 배열 합 구하는 공식을 알고 있다면 어렵지 않은 문제이다.근데 공식이 자꾸 안 외워진다.

profile
개발자로 취직을 희망합니다.

0개의 댓글