ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

1182๋ฒˆ: ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ

์ฒซ์งธ ์ค„์— ์ •์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” N๊ณผ ์ •์ˆ˜ S๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 20, |S| ≤ 1,000,000) ๋‘˜์งธ ์ค„์— N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜์˜ ์ ˆ๋Œ“๊ฐ’์€ 100,000์„ ๋„˜์ง€ ์•Š๋Š”๋‹ค.

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 N๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์—์„œ ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ์ด S๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ด๋Š” ์กฐํ•ฉ์„ ๊ตฌํ•˜๊ณ  ๋ฐœ์ƒํ•œ ๊ฐ ์กฐํ•ฉ ์ค‘ ํ•ฉ์ด S๋ฅผ ๋งŒ์กฑํ•˜๋Š”์ง€ ์ฐพ์œผ๋ฉด ๋˜๋Š” ๋ฌธ์ œ์ด๋‹ค. N์˜ ๋ฒ”์œ„๊ฐ€ ํฌ์ง€ ์•Š์œผ๋ฏ€๋กœ, ๋‹จ์ˆœํžˆ DFS๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

DFS๋ฅผ ์ด์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

from sys import stdin


def dfs(depth, subtotal):
    global answer

    if depth == n:
        return

    if subtotal + nums[depth] == s:
        answer += 1

    dfs(depth + 1, subtotal + nums[depth])
    dfs(depth + 1, subtotal)


if __name__ == "__main__":
    answer = 0
    n, s = map(int, stdin.readline().split())
    nums = list(map(int, stdin.readline().split()))
    dfs(0, 0)
    print(answer)

 ๊ฐ€์ง€๋ฅผ ๋ป—์œผ๋ฉด์„œ ํ˜„์žฌ์˜ ์ˆ˜๋ฅผ ์„ ํƒํ•˜๊ฑฐ๋‚˜, ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋กœ ๋‚˜๋‰˜๊ฒŒ ๋œ๋‹ค. ๋˜ํ•œ ํ•˜๋‚˜์˜ ์›์†Œ๋งŒ ์„ ํƒ๋˜๋Š” ๊ฒƒ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด `if subtotal + nums[depth] == s`๋ผ๋Š” ์กฐ๊ฑด์ด ํ•„์š”ํ•˜๋‹ค.

 

itertools๋ฅผ ์ด์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

from itertools import combinations

n, s = map(int, input().split())
nums = list(map(int, input().split()))
answer = 0
for i in range(1, n + 1):
    for case in combinations(nums, i):
        if sum(case) == s:
            answer += 1
print(answer)

 ์กฐํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋ฏ€๋กœ ํŒŒ์ด์ฌ์˜ `itertools`๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹จ, ํŠน์ • ์ฝ”๋”ฉํ…Œ์ŠคํŠธ(ex: ์‚ผ์„ฑ)์—์„œ๋Š” ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฏ€๋กœ, DFS๋ฅผ ์ด์šฉํ•œ ๋ฌธ์ œ ํ’€์ด๋ฅผ ํ™œ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€