๐Ÿงฉ Problem Solving/[๋ฐฑ์ค€]

[๋ฐฑ์ค€]11660 ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 5 (python ํŒŒ์ด์ฌ)

์ œ๋ด‰์•„ 2022. 8. 19. 20:42

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

 

11660๋ฒˆ: ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 5

์ฒซ์งธ ์ค„์— ํ‘œ์˜ ํฌ๊ธฐ N๊ณผ ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ํšŸ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 1024, 1 ≤ M ≤ 100,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ํ‘œ์— ์ฑ„์›Œ์ ธ ์žˆ๋Š” ์ˆ˜๊ฐ€ 1ํ–‰๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๋„ค

www.acmicpc.net


๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 2์ฐจ์› ๋ฒ„์ „


์•„์ด๋””์–ด

 

1. ๋ˆ„์  ํ•ฉ ์‚ฌ์šฉ

  • ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 4์™€ ์œ ์‚ฌํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค
  • ๋จผ์ € (0 ,0)์—์„œ (x , y)๊นŒ์ง€์˜ ํ•ฉ์„ arr [x][y]์— ์ €์žฅํ•œ๋‹ค. ๊ทธ๋Ÿผ ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

  • ์ด๊ฑธ ์‚ฌ์šฉํ•ด์„œ ๊ตฌ๊ฐ„ ํ•ฉ์„ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.
  • ์˜ˆ๋ฅผ ๋“ค์–ด (1, 1)์—์„œ (2, 3)๊นŒ์ง€ ๊ตฌํ•˜๋ ค๋ฉด(๋ฌธ์ œ์—์„œ๋Š” 2,2 ~ 3,4) arr [2][3]์—์„œ arr[2][0]๊ณผ arr[0][3]๋ฅผ ๋นผ๊ณ  arr[0][0]์„ ๋”ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

์ „์ฒด ์ฝ”๋“œ

import sys
N, M = map(int, input().split())

arr = []

for _ in range(N):
    arr.append([int(x) for x in sys.stdin.readline().rstrip().split()])

for i in range(N):
    for j in range(1, N):
        arr[i][j] += arr[i][j - 1]

for j in range(N):
    for i in range(1, N):
        arr[i][j] += arr[i - 1][j]
        
for _ in range(M):
    ans = 0
    x1, y1, x2, y2 = map(int, sys.stdin.readline().rstrip().split())

    x1 -= 1
    x2 -= 1
    y1 -= 1
    y2 -= 1 # ์ขŒํ‘œ ์กฐ์ •

    ans += arr[x2][y2]

    if x1 - 1 >= 0:
        ans -= arr[x1 - 1][y2]

    if y1 - 1 >= 0:
        ans -= arr[x2][y1 - 1]

    if x1 - 1 >= 0 and y1 - 1 >= 0:
        ans += arr[x1 - 1][y1 - 1]

    print(ans)

์ฝ”๋“œ ์„ค๋ช…

import sys
N, M = map(int, input().split())

arr = []

for _ in range(N):
    arr.append([int(x) for x in sys.stdin.readline().rstrip().split()])

for i in range(N):
    for j in range(1, N):
        arr[i][j] += arr[i][j - 1]

for j in range(N):
    for i in range(1, N):
        arr[i][j] += arr[i - 1][j]

์œ„์— ์„ค๋ช…ํ•œ ๋ฐฐ์—ด์„ ๋งŒ๋“œ๋Š” ๊ณผ์ •์ด๋‹ค. 

2์ฐจ์› ๋ฐฐ์—ด์—์„œ ๋ˆ„์ ํ•ฉ์„ ๊ตฌํ•˜๋ ค๋ฉด ํ–‰์„ ๊ธฐ์ค€์œผ๋กœ ํ•œ๋ฒˆ, ์—ด์„ ๊ธฐ์ค€์œผ๋กœ ํ•œ๋ฒˆ ๋ˆ„์ ํ•ด์„œ ๋”ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

for _ in range(M):
    ans = 0
    x1, y1, x2, y2 = map(int, sys.stdin.readline().rstrip().split())

    x1 -= 1
    x2 -= 1
    y1 -= 1
    y2 -= 1 # ์ขŒํ‘œ ์กฐ์ •

    ans += arr[x2][y2]

    if x1 - 1 >= 0:
        ans -= arr[x1 - 1][y2]

    if y1 - 1 >= 0:
        ans -= arr[x2][y1 - 1]

    if x1 - 1 >= 0 and y1 - 1 >= 0:
        ans += arr[x1 - 1][y1 - 1]

    print(ans)

๋ฌธ์ œ์—์„œ๋Š” (1,1)๋ถ€ํ„ฐ ์‹œ์ž‘์ด๋ฏ€๋กœ ๊ฐ ์ขŒํ‘œ์—์„œ -1 ํ•ด์ค€๋‹ค.

 

๊ทธ๋ฆฌ๊ณ  ์œ„์—์„œ ์„ค๋ช…ํ•œ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

๋‹จ, ๋ฐฐ์—ด์˜ index๋ฅผ ๋„˜์–ด๊ฐ€๋ฉด ์•ˆ ๋˜๋ฏ€๋กœ ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•ด์„œ ์ˆ˜ํ–‰ํ•œ๋‹ค.