Problem Solving/BOJ & Programmers

[BOJ] 1806๋ฒˆ: Subsequence (๋ถ€๋ถ„ํ•ฉ)

geum 2021. 7. 13. 23:13

์ž์‹ ๊ฐ MAX๋กœ ๊ณจ๋“œ ๋ฌธ์ œ์— ๋„์ „ํ–ˆ๋‹ค๊ฐ€ ์‹ค๋ฒ„ ๋ฌธ์ œ๋กœ ๊ฒฝํ—˜์น˜ ๋” ์Œ“์ž๋Š” ์ƒ๊ฐ์„ ํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค โ— ์—ฌ๋Ÿฌ ๋ธ”๋กœ๊ทธ๋ฅผ ์ฐธ๊ณ ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‚˜์ค‘์— ๋‹ค๋ฅธ ์–ธ์–ด๋กœ ๋‹ค์‹œ ํ’€์–ด๋ด์•ผ๊ฒ ๋‹ค.


๋ฌธ์ œ

๋ถ€๋ถ„ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๊ฑธ ๋ดค์„ ๋•Œ ์ „ํ˜•์ ์ธ ํˆฌ ํฌ์ธํ„ฐ ์œ ํ˜•์ด๋‹ค.

 

 

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

๋‹ค๋ฅธ ํˆฌํฌ์ธํ„ฐ ์œ ํ˜• ๋ฌธ์ œ๋“ค์ฒ˜๋Ÿผ ์ž…์ถœ๋ ฅ ์˜ˆ์‹œ๊ฐ€ ๋งค์šฐ ๊ฐ„๋‹จํ•จ

 

 

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

 

1) start, end, total(S์™€ ๋น„๊ตํ•  ๋ถ€๋ถ„ํ•ฉ ์ €์žฅ ๋ณ€์ˆ˜) ์ดˆ๊ธฐํ™”

 

2) start, end ์ด๋™ ๋ฐฉํ–ฅ ์ƒ๊ฐ

โ—ฝ ๋‘˜๋‹ค ์ธ๋ฑ์Šค๊ฐ€ ์ปค์ง€๋Š” ๋ฐฉํ–ฅ

โ—ฝ start๋Š” ์ธ๋ฑ์Šค๊ฐ€ ์ปค์ง€๋Š” ๋ฐฉํ–ฅ, end๋Š” ์ธ๋ฑ์Šค๊ฐ€ ์ž‘์•„์ง€๋Š” ๋ฐฉํ–ฅ

→ ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ์ตœ์†Œ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋‘˜๋‹ค ์ธ๋ฑ์Šค๊ฐ€ ์ฆ๊ฐ€ํ•˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ๊ฐ’์„ ๋ฐ”๊พธ๋Š” ๊ฒŒ ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.

 

3) start, end ๊ฐ’ ๋ณ€ํ™” ์กฐ๊ฑด ์„ค์ • ๋ฐ ์ˆ˜์—ด ๊ธธ์ด ํ™•์ธ

โ—ฝ total >= S → ์ผ๋‹จ ์ •๋‹ต ํ›„๋ณด๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์— ํ™•์ธ ํ›„ ๋‹ค์Œ ์ˆซ์ž๋กœ ๋„˜์–ด๊ฐ€๊ธฐ ์œ„ํ•ด start += 1

โ—ฝ ํ˜„์žฌ answer ๊ฐ’๊ณผ ์œ„์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ๋ถ€๋ถ„ ํ•ฉ ์ˆ˜์—ด์„ ๋งŒ๋‚ฌ์„ ๋•Œ ์ˆ˜์—ด ๊ธธ์ด๋ฅผ ๋น„๊ตํ•˜๊ณ  ๋” ์ž‘์€ ๊ฐ’์œผ๋กœ answer ๊ฐฑ์‹ 

โ—ฝ total < S → total ๊ฐ’์— arr[end] ๊ฐ’์„ ๋”ํ•ด์ฃผ๊ณ  end += 1

 

4) ํ™•์ธ์ด ๋๋‚˜๋Š” ์กฐ๊ฑด ์„ค์ •

โ—ฝ end == N์ผ ๊ฒฝ์šฐ ๋๊นŒ์ง€ ๋‹ค ํ™•์ธํ•œ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— while๋ฌธ์„ ๋น ์ ธ๋‚˜์˜จ๋‹ค.

 

 

์ „์ฒด ์ฝ”๋“œ

# Gold 4

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

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

start, end = 0, 0

total = 0

# ์ž„์˜์˜ ํฐ ๊ฐ’์œผ๋กœ ์ง€์ •
answer = 100001

while True:
    if total >= s:
        total -= arr[start]
        answer = min(answer, end-start)
        start += 1
    else:
        if end == n:
            break
        else:
            total += arr[end]
            end += 1

# ์ดˆ๊ธฐ๊ฐ’์ด ๊ทธ๋Œ€๋กœ๋ผ๋ฉด ๋‹ต์„ ์ฐพ์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ์ด๊ธฐ ๋•Œ๋ฌธ์— 0 ์ถœ๋ ฅ
if answer == 100001:
    print(0)
else:
    print(answer)

 

ํˆฌ ํฌ์ธํ„ฐ ์œ ํ˜• ๋ฌธ์ œ์—์„œ ์ธ๋ฑ์Šค ๊ฐ’์ด start์ผ ๋•Œ๊นŒ์ง€์˜ ๊ฐ’์„ ๋นผ๋Š” ์ฝ”๋“œ๊ฐ€ ์ข…์ข… ๋ณด์ด๋Š”๋ฐ ์‚ฌ์‹ค ์ € ์˜๋ฏธ๋ฅผ ์ •ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ•˜์ง€ ๋ชปํ–ˆ๋‹ค. ๊ณ„์† ๋”ํ•ด๋‚˜๊ฐ€๋Š” ๋ฐฉ์‹์ด ํŽธํ•ด์„œ ๊ทธ๋ ‡๊ฒŒ ์“ฐ๊ณ  ์žˆ๊ธด ํ•œ๋ฐ ๋„ˆ๋ฌด ํ•œ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•๋งŒ ์“ฐ๋ฉด ์‚ฌ๊ณ  ๋ฐฉ์‹์ด ๊ฑฐ๊ธฐ ๊ฐ‡ํž๊นŒ๋ด ์ดํ•ดํ•˜๋ ค๊ณ  ๋…ธ๋ ฅ ์ค‘์ด๋‹ค. ํˆฌ ํฌ์ธํ„ฐ ์œ ํ˜• ์ด๋ฒˆ์—” ๋ด์คฌ์ง€๋งŒ ๋‹ค์Œ์€ ๊ทธ๋ƒฅ ๋ณด๋‚ด์ง€ ์•Š๊ฒ ๋‹ค ๐Ÿคœ

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

[BOJ] 11256๋ฒˆ: Jelly Bean  (0) 2022.02.03
[BOJ] 5177๋ฒˆ: Format Error!  (0) 2022.02.03
[BOJ] 2003๋ฒˆ: ์ˆ˜๋“ค์˜ ํ•ฉ 2  (0) 2021.07.09
[BOJ] 1991๋ฒˆ: ํŠธ๋ฆฌ ์ˆœํšŒ  (0) 2021.07.07
[BOJ] 1260๋ฒˆ: DFS์™€ BFS  (2) 2021.06.27