CS log

[๋ฐฑ์ค€/python] 1182๋ฒˆ : ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ ๋ณธ๋ฌธ

CS/Algorithm

[๋ฐฑ์ค€/python] 1182๋ฒˆ : ๋ถ€๋ถ„ ์ˆ˜์—ด์˜ ํ•ฉ

sj.cath 2024. 8. 11. 16:08

๐Ÿ“๋ฌธ์ œ

https://www.acmicpc.net/problem/1182

N๊ฐœ์˜ ์ •์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ด ์žˆ์„ ๋•Œ, ํฌ๊ธฐ๊ฐ€ ์–‘์ˆ˜์ธ ๋ถ€๋ถ„์ˆ˜์—ด ์ค‘์—์„œ ๊ทธ ์ˆ˜์—ด์˜ ์›์†Œ๋ฅผ ๋‹ค ๋”ํ•œ ๊ฐ’์ด S๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

๐Ÿ“์ž…๋ ฅ

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

 

๐Ÿ“์ถœ๋ ฅ

์ฒซ์งธ ์ค„์— ํ•ฉ์ด S๊ฐ€ ๋˜๋Š” ๋ถ€๋ถ„์ˆ˜์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

๐Ÿ“ํ’€์ด ๋ฐฉ๋ฒ•

combination ํ•จ์ˆ˜๋ฅผ ์“ด๋‹ค -!

 

๐Ÿ“์ฝ”๋“œ

import sys
from itertools import combinations
N, S = map(int,sys.stdin.readline().split())
arr = list(map(int,input().split()))
cnt = 0
for i in range(1, N+1) :
    comb = combinations(arr,i)
    for c in comb : 
        if sum(c) == S : cnt+=1
print(cnt)

 

๐Ÿ“์‹œ๊ฐ„๋ณต์žก๋„

for๋ฌธ์ด ๋‘ ๊ฐœ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— O(n^2)

๋Œ€์‹  ์ž…๋ ฅ์„ ๋ฐ›์„ ๋•Œ์— sys.stdin.readline()์„ ์‚ฌ์šฉํ•˜์—ฌ ์ตœ๋Œ€ํ•œ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์—ฌ๋ณด๋ ค๊ณ  ํ–ˆ์Œ.

 

๐Ÿ“combination

์กฐํ•ฉ : ์กฐํ•ฉ์ด๋ž€ ์„œ๋กœ ๋‹ค๋ฅธ n๊ฐœ ์ค‘์—์„œ r๊ฐœ(n≥r) ์ทจํ•˜์—ฌ ์กฐ๋ฅผ ๋งŒ๋“ค ๋•Œ, ์ด ํ•˜๋‚˜ํ•˜๋‚˜์˜ ์กฐ๋ฅผ n๊ฐœ ์ค‘์—์„œ r๊ฐœ ์ทจํ•œ ์กฐํ•ฉ์ด๋ผ๊ณ  ํ•œ๋‹ค.

์กฐํ•ฉ์€ ์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š๋Š”๋‹ค. [A, B, C]์˜ ๋ฆฌ์ŠคํŠธ์—์„œ 2๊ฐœ์˜ ์›์†Œ๋ฅผ ๊ณจ๋ผ ๋‚˜์—ดํ•˜๋ฉด

[(A, B), (A, C), (B, C)] ๊ฐ€ ๋‚˜์˜ค๊ฒŒ ๋œ๋‹ค. ์กฐํ•ฉ์€ (A, B)์™€ (B, A)๋Š” ๊ฐ™์€ ๊ฒƒ์œผ๋กœ ์ทจ๊ธ‰ํ•œ๋‹ค.

from itertools import combinations

arr = ['A', 'B', 'C']
nCr = combinations(arr, 2)
print(list(nCr))

>>> [('A', 'B'), ('A', 'C'), ('B', 'C')]