[SWEA] 2001. ํ๋ฆฌ ํด์น (DP)
โ๏ธ ๋ฌธ์ ์์ฝ
SW Expert Academy
SW ํ๋ก๊ทธ๋๋ฐ ์ญ๋ ๊ฐํ์ ๋์์ด ๋๋ ๋ค์ํ ํ์ต ์ปจํ ์ธ ๋ฅผ ํ์ธํ์ธ์!
swexpertacademy.com
N x N ๋ฐฐ์ด ์์ ์ซ์๋ ํด๋น ์์ญ์ ์กด์ฌํ๋ ํ๋ฆฌ์ ๊ฐ์๋ฅผ ์๋ฏธํ๋ค.
M x M ํฌ๊ธฐ์ ํ๋ฆฌ์ฑ๋ฅผ ํ ๋ฒ ๋ด๋ฆฌ์ณ ์ต๋ํ ๋ง์ ํ๋ฆฌ๋ฅผ ์ฃฝ์ด๊ณ ์ ํ ๋, ์ฃฝ์ ํ๋ฆฌ์ ๊ฐ์๋ฅผ ๊ตฌํ์ฌ๋ผ.
๐ช ๋ฌด์ํ๊ฒ ํ๊ธฐ (๋ฐ๋ณต๋ฌธ)
์ ์ฌ๊ฐํ์ ์์ ์ ์ (i, j)๋ก ๋๊ณ ๋ชจ๋ ๊ฒฝ์ฐ์์ ํฉ์ ๊ตฌํ๋ค.
๋ฌด๋ ค 4์ค for๋ฌธ์ด๋ค..๐ฑ ๋ฌธ์ ์์ N ์ 5 ์ด์ 15 ์ดํ์ด๊ธฐ ๋๋ฌธ์ ๋ฌด๋ฆฌ ์์ด ํ ์คํธ ์ผ์ด์ค๋ ํต๊ณผํ๋ค.
import sys
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
# ๋ณด๋(B)์์ (x, y)๋ถํฐ ํ ๋ณ์ ๊ธธ์ด๊ฐ size์ธ ์ ์ฌ๊ฐํ ํฉ
def calc(B, x, y, sz):
tot = 0
for i in range(x, x+sz):
for j in range(y, y+sz):
tot += B[i][j]
return tot
if __name__ == '__main__':
T = int(input())
for test_case in range(1, T + 1):
N, M = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(N)]
mx = -1e9
for i in range(N-M+1):
for j in range(N-M+1):
mx = max(mx, calc(board, i, j, M))
print('#{} {}'.format(test_case, mx))
โจ ์ฐ์ํ๊ฒ ํ๊ธฐ (DP)
N*N๋ฐฐ์ด์์, M*M์ ๋ถ๋ถํฉ์ด ๊ฐ์ฅ ํฐ ๊ตฌ๊ฐ์ ์ฐพ๋ ๋ฌธ์
๋ถ๋ถํฉ์ ๋ญ๋ค? DP๋ค
1) ๋ถ๋ถ ํฉ(`total`) ๋ฏธ๋ฆฌ ๊ตฌํด๋๊ธฐ
2) ์ฃผ์ด์ง ๋ฒ์์์ ์ ์ฌ๊ฐํ ํฉ ๊ตฌํ๊ธฐ
์ง์ฌ๊ฐํ ๋ฐฐ์ด์์ ์ด๋ ๋ถ๋ถ์ด ์ค๋ณต ๊ณ์ฐ๋ ์ง ์ฒดํฌํ๋ฉด ํ ์ ์๋ ๋ฌธ์ !
O(n^2)์ ์๊ฐ๋ณต์ก๋ ์์ ํด๊ฒฐ ๊ฐ๋ฅํ๋ค.
import sys
sys.stdin = open("input.txt", "r")
sys.stdout = open("output.txt", "w")
if __name__ == '__main__':
T = int(input())
for test_case in range(1, T + 1):
N, M = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(N)]
tot = [[0] * N for _ in range(N)] # (0,0)~(n,n)์ ์ง์ฌ๊ฐํ ํฉ์ ์ ์ฅํ๋ total ๋ฆฌ์คํธ
# ๋ถ๋ถํฉ ๋ฏธ๋ฆฌ ๊ตฌํด๋๊ธฐ
for i in range(N):
for j in range(N):
tot[i][j] = board[i][j]
if i>0:
tot[i][j] += tot[i-1][j]
if j>0:
tot[i][j] += tot[i][j-1]
if i>0 and j>0:
tot[i][j] -= tot[i-1][j-1]
# ์ฃผ์ด์ง ๋ฒ์์์ ์ ์ฌ๊ฐํ ํฉ ๊ตฌํ๊ธฐ
mx = -1e9
for i in range(N-M+1):
for j in range(N-M+1):
# ์ด๋ (i, j)๋ ์ ์ฌ๊ฐํ ์์์
ii, jj = i+M-1, j+M-1 # (ii, jj)๋ ์ ์ฌ๊ฐํ ๋์
if i==0 and j==0:
tmp = tot[ii][jj]
elif i==0:
tmp = tot[ii][jj] - tot[ii][jj-M]
elif j==0:
tmp = tot[ii][jj] - tot[ii-M][jj]
else:
tmp = tot[ii][jj] - tot[ii][jj-M] - tot[ii-M][jj] + tot[ii-M][jj-M]
mx = max(mx, tmp)
print('#{} {}'.format(test_case, mx))
๐ ์ฐธ๊ณ
SWEA 2001๋ฒ: ํ๋ฆฌ ํด์น/DP