๐Ÿ•๏ธ ICPC Sinchon/Prefix Sum

[C++][BOJ] ๋ฐฑ์ค€ 2167๋ฒˆ: 2์ฐจ์› ๋ฐฐ์—ด์˜ ํ•ฉ

์„ ๋‹ฌ 2024. 8. 8. 17:50
๋ฐ˜์‘ํ˜•

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

 

๋ฌธ์ œ

2์ฐจ์› ๋ฐฐ์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ (i, j) ์œ„์น˜๋ถ€ํ„ฐ (x, y) ์œ„์น˜๊นŒ์ง€์— ์ €์žฅ๋˜์–ด ์žˆ๋Š” ์ˆ˜๋“ค์˜ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ๋ฐฐ์—ด์˜ (i, j) ์œ„์น˜๋Š” iํ–‰ j์—ด์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ๋ฐฐ์—ด์˜ ํฌ๊ธฐ N, M(1 ≤ N, M ≤ 300)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” M๊ฐœ์˜ ์ •์ˆ˜๋กœ ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๋ฐฐ์—ด์— ํฌํ•จ๋˜์–ด ์žˆ๋Š” ์ˆ˜๋Š” ์ ˆ๋Œ“๊ฐ’์ด 10,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜์ด๋‹ค. ๊ทธ ๋‹ค์Œ ์ค„์—๋Š” ํ•ฉ์„ ๊ตฌํ•  ๋ถ€๋ถ„์˜ ๊ฐœ์ˆ˜ K(1 ≤ K ≤ 10,000)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ K๊ฐœ์˜ ์ค„์—๋Š” ๋„ค ๊ฐœ์˜ ์ •์ˆ˜๋กœ i, j, x, y๊ฐ€ ์ฃผ์–ด์ง„๋‹ค(1 ≤ i ≤ x ≤ N, 1 ≤ j ≤ y ≤ M).

์ถœ๋ ฅ

K๊ฐœ์˜ ์ค„์— ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์˜ ํ•ฉ์„ ์ถœ๋ ฅํ•œ๋‹ค. ๋ฐฐ์—ด์˜ ํ•ฉ์€ 231-1๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค.

 

ํ’€์ด

// ํ’€์ด : https://whkakrkr.tistory.com

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    vector<vector<int>> input(n+1, vector<int>(m+1));
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=m; j++) {
            cin >> input[i][j];
        }
    }
    
    // ๋ˆ„์ ํ•ฉ ๊ตฌํ•˜๊ธฐ
    vector<vector<int>> sum(n+1, vector<int>(m+1));
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=m; j++) {
            sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + input[i][j];
        }
    }

    int k, i,j,x,y;
    cin >> k;
    while(k--) {
        cin >> i >> j >> x >> y;
        cout << sum[x][y] - sum[i-1][y] - sum[x][j-1] + sum[i-1][j-1] << "\n";
    }
    
    return 0;
}
๋ฐ˜์‘ํ˜•