[๐Ÿ™ ์•Œ๊ณ ๋ฆฌ์ฆ˜] ๋ฐฑ์ค€ 11660 - ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ5 / Python

dsfasdยท2022๋…„ 10์›” 19์ผ
0

๋ฌธ์ œ

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์ด๋‹ค.

ํ‘œ์— ์ฑ„์›Œ์ ธ ์žˆ๋Š” ์ˆ˜์™€ ํ•ฉ์„ ๊ตฌํ•˜๋Š” ์—ฐ์‚ฐ์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.


์ฝ”๋“œ

# ๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ 5
import sys
input = sys.stdin.readline 
# ๋ชจ๋“  input์— ๋Œ€ํ•œ ๊ฐ’์„ ๋น ๋ฅด๊ฒŒ ์ž…๋ ฅ ๋ฐ›๋Š”๋‹ค.
N,M = map(int,input().split()) 
# ๋ฐฐ์—ด์˜ ํฌ๊ธฐ N,๋ฆฌ์ŠคํŠธ๋ฅผ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ํšŸ์ˆ˜ M

# ๋ฐฐ์—ด ์ž…๋ ฅ๋ฐ›๊ธฐ
arr = [[0]*(N+1)]
for i in range(0,N):
    row = [0] + [int(x) for x in input().split()]
    arr.append(row)

# ํ•ฉ ๋ฐฐ์—ด์„ ๊ตฌํ•˜๊ธฐ
arrSum = [[0]*(N+1) for _ in range(N+1)]
for i in range(1,N+1):
    for j in range(1,N+1):
        arrSum[i][j] = arrSum[i][j - 1] + arrSum[i - 1][j] - arrSum[i - 1][j - 1] + arr[i][j]

ans = 0
#์ขŒํ‘œ์— ๋งž๋Š” ๊ฐ’์„ ์ฐพ์•„์„œ ๋‹ต์„ ์ถœ๋ ฅํ•˜๊ธฐ
for _ in range(M): #ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งŒํผ
    #์ฒ˜์Œ ์ขŒํ‘œ์—์„œ ์‹œ์ž‘ํ•ด์„œ
    x1,y1,x2,y2 = map(int,input().split())
    ans = arrSum[x2][y2]-arrSum[x1-1][y2]-arrSum[x2][y1-1]+arrSum[x1-1][y1-1]
    print(ans)

ํ’€์ด

์งˆ์˜์˜ ๊ฐœ์ˆ˜๊ฐ€ 100,000๊ฐœ ์ด๋ฏ€๋กœ ํ•ฉ๋ฐฐ์—ด์„ ๊ตฌํ•˜์—ฌ ํ’€์–ด์•ผ ํ•œ๋‹ค๋Š” ์ ์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

ํ•ฉ๋ฐฐ์—ด์˜ ๊ธฐ๋ณธ ์•„์ด๋””์–ด๋Š” ์ „์ฒดํ•ฉ๋ฐฐ์—ด(ํฐ๋ถ€๋ถ„) - ๋นผ์•ผํ•  ๋ถ€๋ถ„(์ž‘์€๋ถ€๋ถ„)์ด๋‹ค.

์ด์ฐจ์› ๋ฆฌ์ŠคํŠธ์˜ ํ•ฉ๋ฐฐ์—ด์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด์„œ ์ขŒํ‘œ๋ฅผ ๊ฐ๊ฐ ์ž…๋ ฅ๋ฐ›์•„์„œ ๋นผ์•ผํ•  ๋ถ€๋ถ„๋งŒ ๋นผ์ฃผ์—ˆ๋‹ค.

TypeError: 'int' object is not subscriptable ์—๋Ÿฌ

์ค‘๊ฐ„์— ์ € ์—๋Ÿฌ๊ฐ€ ๋‚˜์„œ ๊ฝค๋‚˜ ๊ณ ์ƒํ–ˆ๋Š”๋ฐ,, ์•Œ๊ณ ๋ณด๋‹ˆ for๋ฌธ์—์„œ ๋ณ€์ˆ˜๋ฅผ k๋กœ ์จ๋†“๊ณ  i๋กœ ์ธ๋ฑ์‹ฑ์„ ํ• ๋‹นํ•ด์ค˜์„œ ๋‚˜๋Š” ์—๋Ÿฌ์˜€๋‹ค..^^

profile
๊ธฐ๋ก์„ ์ •๋ฆฌํ•˜๋Š” ๊ณต๊ฐ„!

0๊ฐœ์˜ ๋Œ“๊ธ€