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

[BOJ][C++] ๋ฐฑ์ค€ 11660๋ฒˆ : ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 5

์„ ๋‹ฌ 2024. 8. 8. 18:14
๋ฐ˜์‘ํ˜•

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

 

๋ฌธ์ œ

N×N๊ฐœ์˜ ์ˆ˜๊ฐ€ N×N ํฌ๊ธฐ์˜ ํ‘œ์— ์ฑ„์›Œ์ ธ ์žˆ๋‹ค. (x1, y1)๋ถ€ํ„ฐ (x2, y2)๊นŒ์ง€ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. (x, y)๋Š” xํ–‰ y์—ด์„ ์˜๋ฏธํ•œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, N = 4์ด๊ณ , ํ‘œ๊ฐ€ ์•„๋ž˜์™€ ๊ฐ™์ด ์ฑ„์›Œ์ ธ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ์‚ดํŽด๋ณด์ž.

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

์—ฌ๊ธฐ์„œ (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)๊นŒ์ง€ ํ•ฉ์„ ๊ตฌํ•ด ์ถœ๋ ฅํ•œ๋‹ค.

 

ํ’€์ด

์‹œ๊ฐ„์ œํ•œ์ด ๋นก์„ผ ๋ฌธ์ œ๋‹ค.

์ถœ์ œ์ž๊ฐ€ ์˜๋„ํ•œ ๋ˆ„์ ํ•ฉ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•œ O(n)ํ’€์ด๋ฅผ ์ง„ํ–‰ํ•˜๋”๋ผ๋„

sync_with_stdio ์ด๊ฑฐ ์•ˆ์“ฐ๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚œ๋‹ค.

ios_base::sync_with_stdio(false);
cout.tie(NULL);
cin.tie(NULL);

 

์ฝ”๋“œ

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

#include <iostream>
#include <vector>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
	cout.tie(NULL);
	cin.tie(NULL);
	
    int n, m;
    cin >> n >> m;
    vector<vector<int>> v(n+1, vector<int>(n+1));
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++) {
            cin >> v[i][j];
        }
    }
    
    // ๊ตฌ๊ฐ„ํ•ฉ ๊ตฌํ•˜๊ธฐ
    vector<vector<int>> sum(n+1, vector<int>(n+1));
    for(int i=1; i<=n; i++) {
        for(int j=1; j<=n; j++) {
            sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + v[i][j];
        }
    }
    
    int x1, y1, x2, y2;
    while(m--) {
        cin >> x1 >> y1 >> x2 >> y2;
        int partial = sum[x2][y2] - sum[x1-1][y2] - sum[x2][y1-1] + sum[x1-1][y1-1];
        cout << partial << "\n";
    }
    
    return 0;
}
๋ฐ˜์‘ํ˜•