๐Ÿง  Prefix   Sum 

Prefix Sum, ๊ตฌ๊ฐ„ํ•ฉ, ๋ˆ„์ ํ•ฉ, ๋ถ€๋ถ„ํ•ฉ์ด๋ผ ๋ถˆ๋ฆฌ๋ฉฐ ํ•ด๋‹น ๊ตฌ๊ฐ„์— ๋Œ€ํ•œ ํ•ฉ์„ ๋น ๋ฅด๊ฒŒ ๊ตฌํ•˜๊ธฐ ์œ„ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋งค์šฐ ๊ฐ„๋‹จํ•˜๋‹ค.

์›๋ฆฌ๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.
1. ํ•ฉ ๋ฐฐ์—ด S๋ฅผ ๋งŒ๋“œ๋Š” ๊ณต์‹
S[i] = S[i-1] + a[i]

2. i~j๊นŒ์ง€์˜ ๊ตฌ๊ฐ„ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๊ณต์‹
S[j] - S[i-1]


์ด๋ฅผ ์ด์šฉํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ผ์ • ๊ตฌ๊ฐ„์—์„œ์˜ ํ•ฉ์„ ๋น ๋ฅด๊ฒŒ (์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์ด๋ฉด์„œ) ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

  S[5] = A[0] + A[1] + A[2] + A[3] + A[4] + A[5]
  S[1] = A[0] + A[1]
--------------------------------------------------
∴ S[5] - S[1] = A[2] + A[3] + A[4] + A[5]

 

 

๐Ÿง ๋ฐฑ์ค€ 11659 (๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ)    Silver III 




๐Ÿคซ  solution_11659

n, m = map(int, input().split())
num = list(map(int, input().split()))

prefix_sum = [0]
p_sum = 0
for i in num:
    p_sum += i
    prefix_sum.append(p_sum)


for _ in range(m):
    i, j = map(int, input().split())
    print(prefix_sum[j] - prefix_sum[i-1])

 

 

 

๐Ÿง ๋ฐฑ์ค€ 11660(๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ _ ์ด์ฐจ์› ๋ฐฐ์—ด)    Silver I 



๐Ÿคซ  Algorithm 

 


๐Ÿคซ  solution_11660

n, m = map(int, input().split())
num = [list(map(int, input().split())) for i in range(n)]

S = [[0 for i in range(n + 1)] for i in range(n + 1)]

for i in range(n):
    for j in range(n):
        S[i + 1][j + 1] = (S[i][j + 1] + S[i + 1][j] - S[i][j]) + num[i][j]

for i in range(m):
    x1, y1, x2, y2 = map(int, input().split())
    print(S[x2][y2] - (S[x2][y1-1] + S[x1-1][y2]) + S[x1-1][y1-1])

 

 

 

๐Ÿง ๋ฐฑ์ค€ 10986(๊ตฌ๊ฐ„ ํ•ฉ ๊ตฌํ•˜๊ธฐ)    Gold III 


๋ถ€๋ถ„ ํ•ฉ ๊ฐœ๋…์„ ์ด์šฉํ•ด์„œ ํ’€ ๋•Œ, ๋ถ€๋ถ„ ํ•ฉ์„ ๊ณ„์‚ฐํ•œ ๋ฐฐ์—ด์„ i, j๋กœ ์ˆœ์ฐจ์ ์œผ๋กœ ์ ‘๊ทผํ•  ๊ฒฝ์šฐ 
O(n^2)์œผ๋กœ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฏ€๋กœ ๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ๋ฒ•์ด ํ•„์š”ํ•˜๋‹ค.

๐Ÿคซ  Algorithm 

๋ฏธ๋ฆฌ ๊ตฌํ•ด๋‘” prefix sum์—์„œ์˜ ๋ถ€๋ถ„ํ•ฉ์€ S[j] - S[i - 1]์˜ ๊ณผ์ •์ด๋‹ค.

์ด๋•Œ, S[j]์™€ S[i-1]์ด ๊ฐ๊ฐ m์œผ๋กœ ๋‚˜๋ˆด์„ ๋•Œ์˜ ๋‚˜๋จธ์ง€๊ฐ€ ๋™์ผํ•˜๋‹ค๋ฉด?
S[j] - S[i - 1] ์—ฐ์‚ฐ ํ›„ ๋‚˜๋จธ์ง€๋Š” 0์ด ๋˜๊ธฐ์— m์œผ๋กœ ๋‚˜๋ˆ  ๋–จ์–ด์ง„๋‹ค.

๊ฒฐ๊ตญ m์œผ๋กœ ๋‚˜๋ˆ ๋–จ์–ด์ง€๋Š” ๋ถ€๋ถ„ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๊ฒƒ์€ 
๋‚˜๋จธ์ง€๊ฐ€ ๋™์ผํ•œ idx ์ค‘ ์ž„์˜๋กœ nC2๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์œผ๋ฏ€๋กœ ๋‹ค์Œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ฑฐ์นœ๋‹ค.

[1] [2] [3] [1] [2] -> [0] [1] [3] [6] [7] [9] -> [0] [1] [0] [0] [1] [0] 
-> [0 : 4, 1 : 2] -> 6 + 1 -> 7

 


๐Ÿคซ  solution_10986

import sys
input = sys.stdin.readline

n, m = map(int, input().split())
num_list = list(map(int, input().split()))

rest_list = [0 for _ in range(m)]
rest_list[0] = 1

prefix_sum = 0
for i in range(n):
    prefix_sum += num_list[i]
    rest = prefix_sum % m
    # ๋‚˜๋จธ์ง€ ๊ฐ’์— ๋”ฐ๋ผ์„œ idx ์ •๋ณด ์ €์žฅ
    rest_list[rest] += 1

cnt = 0
for i in rest_list:
    cnt += i*(i - 1) // 2

print(cnt)

 

 

 

+ Recent posts