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

2021. 9. 20. 02:46

๋ฌธ์ œ

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

 

์ •๋‹ต

import sys
input = sys.stdin.readline

N, M = map(int, input().split())
# board์˜ ๊ฐ€๋กœ ์„ธ๋กœ ์ฒซ ์ค„์€ 0์œผ๋กœ ์ดˆ๊ธฐํ™”. board์˜ ๊ธธ์ด๋Š” N+1์ด ๋˜๊ณ  ๊ฐ’์€ (1,1)๋ถ€ํ„ฐ ์žˆ๋‹ค.
board = [[0 for _ in range(N+1)]]
for _ in range(N):
    board.append([0])
    board[-1].extend(list(map(int, input().split())))

for i in range(1, N+1):
    for j in range(1, N+1):
        board[i][j] += board[i-1][j] + board[i][j-1] - board[i-1][j-1]
        
for _ in range(M):
    x1, y1, x2, y2 = map(int, input().split())
    print(board[x2][y2] - board[x1-1][y2] - board[x2][y1-1] + board[x1-1][y1-1])

์ธ๋ฑ์Šค ํŽธ์˜๋ฅผ ์œ„ํ•ด board์˜ ๊ฐ€๋กœ ์ฒซ์ค„๊ณผ ์„ธ๋กœ ์ฒซ์ค„์„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ฃผ์—ˆ๋‹ค.

์ž…๋ ฅ๋ฐ›๋Š” ๊ฐ’์€ board์˜ (1,1)๋ถ€ํ„ฐ ๋“ค์–ด๊ฐ€๊ฒŒ ๋œ๋‹ค.

 

๋ชจ๋“  ์ž…๋ ฅ์„ ๋ฐ›์€ ํ›„ board์˜ ๊ฐ’์„ (0, 0)์—์„œ ํ•ด๋‹น ์ธ๋ฑ์Šค๊นŒ์ง€์˜ ์ˆซ์ž ํ•ฉ์œผ๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

์ฒซ์ค„์„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ด์ฃผ์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜๋ณต๋ฌธ์˜ ๋ฒ”์œ„๋ฅผ 1๋ถ€ํ„ฐ N+1๊นŒ์ง€๋กœ ํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

(i, j)์˜ ๊ฐ’์€ (i-1, j)์˜ ๊ฐ’ + (i, j-1)์˜ ๊ฐ’์—์„œ ์ค‘๋ณต๋˜๋Š” (i-1, j-1)์˜ ๊ฐ’์„ ๋บ€ ๊ฐ’์ด๋‹ค.

 

M๊ฐœ์˜ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ๊ณ„์‚ฐํ•œ๋‹ค.

board์˜ ๊ฐ’์„ ๋ฐ”๊ฟ”์ค„ ๋•Œ์™€ ์œ ์‚ฌํ•œ ๋…ผ๋ฆฌ๋กœ

(x1, y1)์—์„œ (x2, y2) ๋ฒ”์œ„์˜ ๊ฐ’์„ ๊ณ„์‚ฐํ•œ๋‹ค.

 

 

728x90

BELATED ARTICLES

more