Problem Solving/BOJ & Programmers

[BOJ] 2003๋ฒˆ: ์ˆ˜๋“ค์˜ ํ•ฉ 2

geum 2021. 7. 9. 18:12

1์ผ 1์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€ ์ค‘ ์˜ค๋Š˜์˜ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ํˆฌ ํฌ์ธํ„ฐ๋‹ค. ์ผ๋‹จ ๊ณต๋ถ€๋Š” ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜๋“ค์ฒ˜๋Ÿผ ๊ฐœ๋… ์ž์ฒด๋Š” ํฌ๊ฒŒ ์–ด๋ ต์ง€ ์•Š์•˜๋‹ค. ํ•ญ์ƒ ์‘์šฉ์„ ๋ชปํ•˜๋Š” ๋‚ด๊ฐ€ ๋ฌธ์ œ์ผ ๋ฟ,,^^ ๊ทผ๋ฐ ์ด๋ถ„ํƒ์ƒ‰์ด๋ž‘ ๋น„์Šทํ•œ ๊ฑฐ ๊ฐ™๋‹ค๊ณ  ๋Š๊ปด์„œ ์–ด๋–ค ์ฐจ์ด๊ฐ€ ์žˆ๋Š”์ง€๋Š” ์ข€ ๋” ์ฐพ์•„๋ด์•ผ๊ฒ ๋‹ค.


๋ฌธ์ œ

 

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

 

์•„์ด๋””์–ด ํ๋ฆ„

 

1) ํ•„์š”ํ•œ ๋ณ€์ˆ˜ ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™”

โ—ฝ start, end = 0, 0

โ—ฝ total = 0

โ—ฝ cnt = 0

 

2) total๊ณผ ์ฃผ์–ด์ง„ M ๊ฐ’ ๋น„๊ต

โ—ฝ total == M → cnt += 1, start += 1

โ—ฝ total < M → end += 1

โ—ฝ total > M → start += 1

โ—ฝ ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ํ™•์ธํ•  ๋•Œ๊นŒ์ง€ ์œ„์˜ ๊ณผ์ •์„ ๋ฐ˜๋ณต

 

์ „์ฒด ์ฝ”๋“œ

cnt = 0

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

a = list(map(int, input().split()))

total = 0

start, end = 0, 0

while start <= end and end <= len(a):
    total = sum(a[start:end])

    if total > m:
        start += 1
    elif total < m:
        end += 1
    else:
        cnt += 1
        start += 1

print(cnt)

 

์ฝ”๋“œ๋ฅผ ์ฒ˜์Œ ์งฐ์„ ๋•Œ๋Š” total == M์ผ ๋•Œ cnt ๊ฐ’๋งŒ 1์„ ๋”ํ•ด์ฃผ๊ณ  ํฌ์ธํ„ฐ๋ฅผ ์ด๋™์‹œํ‚ค์ง€ ์•Š์•˜๋Š”๋ฐ ์ž…์ถœ๋ ฅ ์˜ˆ์‹œ๋Œ€๋กœ ๊ฐ’์ด ์•ˆ ๋‚˜์™€์„œ start += 1์„ ์ถ”๊ฐ€ํ•ด์คฌ๋‹ค. end += 1์ผ ๋•Œ๋Š” ์–ด๋–ป๊ฒŒ ๋˜๋‚˜ ์‹ถ์–ด์„œ ๋ฐ”๊ฟ” ์ œ์ถœํ•ด๋ดค๋”๋‹ˆ ์ฑ„์  ํ†ต๊ณผํ•œ ๊ฒƒ์„ ๋ณด๋ฉด total ๊ฐ’์— ๋”ฐ๋ผ ํฌ์ธํ„ฐ๊ฐ€ ์›€์ง์ผ ๊ฑฐ๋‹ˆ๊นŒ totall == M์ธ ๊ฒฝ์šฐ์—์„œ๋Š” ์–ด๋–ค ํฌ์ธํ„ฐ๋ฅผ ์›€์ง์—ฌ๋„ ์ƒ๊ด€์ด ์—†๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

 

์ฐธ๊ณ 

ํˆฌ ํฌ์ธํ„ฐ ๊ฐœ๋… ๋ณธ๋‹ค๊ณ  ์œ ํŠœ๋ธŒ ์˜์ƒ 2๊ฐœ ์ฐพ์•„๋ดค๋Š”๋ฐ ๋‘ ์˜์ƒ ๋‹ค ์ด ๋ฌธ์ œ๋กœ ๊ฐœ๋… ์„ค๋ช…์„ ํ–ˆ๊ณ  ๊ทธ ์ค‘์— ๋‚˜๋™๋นˆ ๋‹˜์˜ ์ฝ”๋“œ๋ฅผ ์ฐธ๊ณ ์šฉ์œผ๋กœ ๊ฐ€์ ธ์™€๋ดค๋‹ค.

# ์˜์ƒ์—์„œ๋Š” n, m, data ๊ฐ’์„ ๊ณ ์ •ํ•˜์…จ๋Š”๋ฐ ์ด ๋ถ€๋ถ„๋งŒ ์ˆ˜์ •
n, m = map(int, input().split())
data = list(map(int, input().split()))

result = 0
summary = 0
end = 0

# start๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ์ฆ๊ฐ€์‹œํ‚ค๋ฉฐ ๋ฐ˜๋ณต
for start in range(n):
    # end๋ฅผ ๊ฐ€๋Šฅํ•œ๋งŒํผ ์ด๋™์‹œํ‚ค๊ธฐ
    while summary < m and end < n:
    	summary += data[end]
        end += 1
    # ๋ถ€๋ถ„ ํ•ฉ์ด m์ผ ๋•Œ ์นด์šดํŠธ ์ฆ๊ฐ€
    if summary == m:
    	result += 1
    
    summary -= data[start]

print(result)

 

start ๋ณ€์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  for๋ฌธ์„ ์ด์šฉํ•œ๋‹ค๋Š” ๊ฒƒ๊ณผ ๋ถ€๋ถ„ ํ•ฉ์—์„œ data[start]๋ฅผ ๋นผ๋Š” ๋ฐฉ์‹์ด ์ธ์ƒ ๊นŠ์—ˆ๋‹ค.

'Problem Solving > BOJ & Programmers' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[BOJ] 11256๋ฒˆ: Jelly Bean  (0) 2022.02.03
[BOJ] 5177๋ฒˆ: Format Error!  (0) 2022.02.03
[BOJ] 1806๋ฒˆ: Subsequence (๋ถ€๋ถ„ํ•ฉ)  (0) 2021.07.13
[BOJ] 1991๋ฒˆ: ํŠธ๋ฆฌ ์ˆœํšŒ  (0) 2021.07.07
[BOJ] 1260๋ฒˆ: DFS์™€ BFS  (2) 2021.06.27