์ƒˆ์†Œ์‹

๐Ÿงฎ ์•Œ๊ณ ๋ฆฌ์ฆ˜/-- ๋ฐฑ์ค€ (BOJ) - Python

๋ฐฑ์ค€ (boj) ํŒŒ์ด์ฌ - 1182 ๋ฒˆ : ๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ

  • -

๋ฌธ์ œ๋งํฌ  :https://www.acmicpc.net/problem/1182

 

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

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

www.acmicpc.net

 

 

 

itertools์˜ combination์„ ์‚ฌ์šฉํ•˜์—ฌ ํ’€์—ˆ๋‹ค. (์ž๋™์œผ๋กœ n๊ฐœ์ค‘์— r๊ฐœ๋ฅผ ๋ฝ‘๋Š” ์กฐํ•ฉ(combination)์„ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š”... )

https://infinitt.tistory.com/114

 

์ˆœ์—ด๊ณผ ์กฐํ•ฉ ( n! , nPr , nCr ) - (itertools) combinations, permutations + ์ค‘๋ณต์ˆœ์—ด, ์ค‘๋ณต์กฐํ•ฉ

*n! (Factorial, ํŒฉํ† ๋ฆฌ์–ผ) 1๋ถ€ํ„ฐ ์ž์—ฐ์ˆ˜ n๊นŒ์ง€์˜ ๋ชจ๋“  ์ˆ˜๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๊ณฑํ•˜๋Š”๊ฒƒ. (์ฃผ์˜ 0! = 1) math๋ชจ๋“ˆ ํŒŒ์ด์ฌ์—์„œ ํŒฉํ† ๋ฆฌ์–ผ์„ ๊ตฌํ• ๋•Œ๋Š” math๋ชจ๋“ˆ์„ ์ด์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค. import math math.factorial(5) *nPr (perm..

infinitt.tistory.com

 

๋ฌธ์ œ์—์„œ N๊ณผ S๋ฅผ ์ž…๋ ฅ์œผ๋กœ ์ค€๋‹ค.

N๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ค‘์—, ?๊ฐœ๋ฅผ ๋ฝ‘์•„ ๊ทธ ํ•ฉ์ด S์™€ ๊ฐ™์•„์•ผ ํ•˜๋ฏ€๋กœ ์กฐํ•ฉ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

from itertools import combinations
N, S = map(int,input().split())
arr = list(map(int,input().split()))
cnt = 0
for i in range(1,len(arr)+1):
    answer = list(combinations(arr,i))


    for idx in range(len(answer)):
        sum_partier = sum(answer[idx])
        if sum_partier == S :
            cnt += 1
    
print(cnt)
    

 

 

 

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.