Post

[SWEA] 5607.[Professional] ์กฐํ•ฉ (python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ์กฐํ•ฉ ๊ณ„์‚ฐ

    ์กฐํ•ฉ๊ด€๋ จ ๋ฌธ์ œ์ด๋ฏ€๋กœ ํŽ™ํ† ๋ฆฌ์–ผ์„ ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ํ•˜์˜€๋‹ค. python์—๋Š” combination๊ฐ’์„ ๊ณ„์‚ฐํ•˜๋Š” math.comb(n,r)ํ•จ์ˆ˜๊ฐ€ ์žˆ์–ด์„œ ์‚ฌ์šฉํ•˜๋ คํ•˜์˜€์ง€๋งŒ n์˜ ์ตœ๋Œ€๊ฐ’์ด 1e6์ด์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜ํƒ€๋‚ฌ๋‹ค. ๊ทธ๋ž˜์„œ ์ง์ ‘ ํŽ™ํ† ๋ฆฌ์–ผ์„ ๊ตฌํ˜„ํ•ด์•ผํ–ˆ๋‹ค.

  2. factorial ๊ตฌํ˜„

    $Combination(n,r) = \frac{n!}{(n-r)!r!}$ ์„ ๊ตฌํ˜„ํ•ด์•ผ ํ–ˆ๊ธฐ์— ์ฒ˜์Œ์—๋Š” ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

1
2
3
def fact(n):
    if n==0 or n==1: return 1
    return n * fact(n-1)

์žฌ๊ท€ ํ˜ธ์ถœ์˜ ๊นŠ์ด ์ œํ•œ์œผ๋กœ ์ธํ•˜์—ฌ ์Šคํƒ ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ ๋‹ค๋ฅธ ๋ฐฉ๋ฒ•์„ ์ฐพ์•„์•ผ ํ–ˆ๋‹ค. ๊ทธ๋ž˜์„œ ๋ฐ‘ ์ฝ”๋“œ์™€ ๊ฐ™์ด memorization๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํŽ™ํ† ๋ฆฌ์–ผ ๊ฐ’์„ ๊ณ„์‚ฐํ•˜์˜€๋‹ค.

1
2
3
4
arr = [1, 1]
def fact(n):
    for i in range(2, n+1):
        arr.append(arr[-1] * i)

ํ…Œ์ŠคํŠธ์ผ€์ด์Šค๋งˆ๋‹ค ํŽ™ํ† ๋ฆฌ์–ผ๋ฐฐ์—ด์„ ๊ตฌํ•˜๋Š” ๊ฒƒ์€ ์ค‘๋ณต๋œ ๊ณ„์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ๋˜์–ด ๋น„ํšจ์œจ์ (O(T*n))์—ˆ๋‹ค. ๊ทธ๋ž˜์„œ ํ…Œ์ด์Šค์ผ€์ด์Šค๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ตœ๋Œ“๊ฐ’์„ ์ฐพ๊ณ  ์ตœ๋Œ“๊ฐ’๋งŒํผ์˜ ํŽ™ํ† ๋ฆฌ์–ผ๋ฐฐ์—ด์„ ๊ตฌํ•˜์—ฌ ์žฌ์‚ฌ์šฉํ•˜์˜€๋‹ค.(ํ•œ๋ฒˆ๋งŒ ํŽ™ํ† ๋ฆฌ์–ผ๋ฐฐ์—ด์„ ์ฐพ์œผ๋ฉด ๋ชจ๋“  ๊ฐ’์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๊ธฐ ๋–„๋ฌธ์ด๋‹ค.(O(n)))

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
arr = [1, 1]
def fact(n):
    for i in range(2, n+1):
        arr.append((arr[-1] * i) % 1234567891)

T = int(input())
li = []
max_val = 0

for i in range(1, T+1):
    n, r = map(int, input().split())
    max_val = max(n, r, max_val)
    li.append((n, r))

fact(max_val)

for i, val in enumerate(li):
    a, b = val
    answer = (arr[a] * pow((arr[a-b] * arr[b]) % 1234567891, 1234567889, 1234567891)) % 1234567891
    print('#{} {}'.format(i+1, answer))
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.