๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[Baekjoon] 1010.๋‹ค๋ฆฌ ๋†“๊ธฐ/Python - Silver5

by The Future Engineer, Lucy 2024. 12. 6.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

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

์„ฑ๋Šฅ ์š”์•ฝ

์ฝ”๋“œ1 โžก๏ธ ์–ธ์–ด:PyPy3, ๋ฉ”๋ชจ๋ฆฌ: 109240 KB, ์‹œ๊ฐ„: 96 ms
์ฝ”๋“œ2 โžก๏ธ ์–ธ์–ด:PyPy3, ๋ฉ”๋ชจ๋ฆฌ: 109240 KB, ์‹œ๊ฐ„: 96 ms
์ฝ”๋“œ1 โžก๏ธ ์–ธ์–ด:Python3, ๋ฉ”๋ชจ๋ฆฌ: 31120 KB, ์‹œ๊ฐ„: 32 ms
์ฝ”๋“œ2 โžก๏ธ ์–ธ์–ด:Python3, ๋ฉ”๋ชจ๋ฆฌ: 31120 KB, ์‹œ๊ฐ„: 32 ms

๋ฌธ์ œ ์„ค๋ช…

์žฌ์›์ด๋Š” ํ•œ ๋„์‹œ์˜ ์‹œ์žฅ์ด ๋˜์—ˆ๋‹ค. ์ด ๋„์‹œ์—๋Š” ๋„์‹œ๋ฅผ ๋™์ชฝ๊ณผ ์„œ์ชฝ์œผ๋กœ ๋‚˜๋ˆ„๋Š” ํฐ ์ผ์ง์„  ๋ชจ์–‘์˜ ๊ฐ•์ด ํ๋ฅด๊ณ  ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ์žฌ์›์ด๋Š” ๋‹ค๋ฆฌ๊ฐ€ ์—†์–ด์„œ ์‹œ๋ฏผ๋“ค์ด ๊ฐ•์„ ๊ฑด๋„ˆ๋Š”๋ฐ ํฐ ๋ถˆํŽธ์„ ๊ฒช๊ณ  ์žˆ์Œ์„ ์•Œ๊ณ  ๋‹ค๋ฆฌ๋ฅผ ์ง“๊ธฐ๋กœ ๊ฒฐ์‹ฌํ•˜์˜€๋‹ค. ๊ฐ• ์ฃผ๋ณ€์—์„œ ๋‹ค๋ฆฌ๋ฅผ ์ง“๊ธฐ์— ์ ํ•ฉํ•œ ๊ณณ์„ ์‚ฌ์ดํŠธ๋ผ๊ณ  ํ•œ๋‹ค. ์žฌ์›์ด๋Š” ๊ฐ• ์ฃผ๋ณ€์„ ๋ฉด๋ฐ€ํžˆ ์กฐ์‚ฌํ•ด ๋ณธ ๊ฒฐ๊ณผ ๊ฐ•์˜ ์„œ์ชฝ์—๋Š” N๊ฐœ์˜ ์‚ฌ์ดํŠธ๊ฐ€ ์žˆ๊ณ  ๋™์ชฝ์—๋Š” M๊ฐœ์˜ ์‚ฌ์ดํŠธ๊ฐ€ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ์•˜๋‹ค. (N ≤ M)

์žฌ์›์ด๋Š” ์„œ์ชฝ์˜ ์‚ฌ์ดํŠธ์™€ ๋™์ชฝ์˜ ์‚ฌ์ดํŠธ๋ฅผ ๋‹ค๋ฆฌ๋กœ ์—ฐ๊ฒฐํ•˜๋ ค๊ณ  ํ•œ๋‹ค. (์ด๋•Œ ํ•œ ์‚ฌ์ดํŠธ์—๋Š” ์ตœ๋Œ€ ํ•œ ๊ฐœ์˜ ๋‹ค๋ฆฌ๋งŒ ์—ฐ๊ฒฐ๋  ์ˆ˜ ์žˆ๋‹ค.) ์žฌ์›์ด๋Š” ๋‹ค๋ฆฌ๋ฅผ ์ตœ๋Œ€ํ•œ ๋งŽ์ด ์ง€์œผ๋ ค๊ณ  ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์„œ์ชฝ์˜ ์‚ฌ์ดํŠธ ๊ฐœ์ˆ˜๋งŒํผ (N๊ฐœ) ๋‹ค๋ฆฌ๋ฅผ ์ง€์œผ๋ ค๊ณ  ํ•œ๋‹ค. ๋‹ค๋ฆฌ๋ผ๋ฆฌ๋Š” ์„œ๋กœ ๊ฒน์ณ์งˆ ์ˆ˜ ์—†๋‹ค๊ณ  ํ•  ๋•Œ ๋‹ค๋ฆฌ๋ฅผ ์ง€์„ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜๋ผ.

โœ๐Ÿปํ’€์ด

DP ๋ฌธ์ œ๋กœ ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฌธ์ œ๋ฅผ ์ฝ์œผ๋ฉด ๋ฐ”๋กœ ์กฐํ•ฉ์ด๋ผ๋Š” ๊ฒƒ์„ ์•Œ ๊ฒƒ์ด๋‹ค.

๐Ÿ’ป์ฝ”๋“œ

import sys

input = sys.stdin.readline
ts = int(input())

res = 0
for _ in range(ts):
    n, m = map(int, input().split())
    dp = [0] * (m+1)
    dp[0] = 1
    dp[1] = m

    for i in range(2, n+1):
        dp[i] = dp[i - 1]*(m-i+1)//i

    print(dp[n])
import sys

input = sys.stdin.readline
ts = int(input())

res = 0
for _ in range(ts):
    n, m = map(int, input().split())
    dp = [0] * (m+1)
    dp[0] = 1
    dp[1] = m

    for i in range(2, (m+1)//2):
        dp[i] = dp[i - 1]*(m-i+1)//i

    if n > m//2:
        print(dp[m-n])
    else:
        print(dp[n])

๐Ÿ“ํ›„๊ธฐ

์ฒ˜์Œ์— ์‹œ๊ฐ„ ์ค„์ผ ์ƒ๊ฐ์œผ๋กœ m/2์ธ ๋ถ€๋ถ„๊นŒ์ง€๋งŒ for๋ฌธ์„ ๋Œ๋„๋ก ์„ค์ •ํ•ด์•ผ์ง€ ํ•ด๋†“๊ณ  ํ‹€๋ ธ๋‹ค. ๊ทธ๋ž˜์„œ ์ด๋ ‡๊ฒŒ ํ’€๋ฉด ์•ˆ ๋˜๋Š” ๊ฑด๊ฐ€ํ•˜๊ณ  n๊นŒ์ง€ ๋‹ค ๋„๋Š” ๊ฑธ๋กœ ๋ฐ”๊ฟจ๋‹ค๊ฐ€ ๋‚ด๊ฐ€ for๋ฌธ ๋ฒ”์œ„๋ฅผ ์ž˜๋ชป ์“ด ๊ฑธ ๊นจ๋‹ซ๊ณ  ๋‹ค์‹œ m/2๊นŒ์ง€ ๋Œ๋ฆฌ๋Š” ๊ฒƒ์œผ๋กœ ํ•ด์„œ ํ’€์—ˆ๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์ „์— ์–ด๋””์„œ PyPy3๋กœ ํ•˜๋Š” ๊ฒŒ ์‹œ๊ฐ„์ด๋ž‘ ๋ฉ”๋ชจ๋ฆฌ ์ ๊ฒŒ ๋“ ๋‹ค๊ณ  ํ–ˆ๋˜ ๊ฒƒ ๊ฐ™์€๋ฐ Python3๋กœ ํ•˜๋Š” ๊ฒŒ ๋” ๋น ๋ฅธ ๊ฒƒ ๊ฐ™๋‹ค. ๋‚ด๊ฐ€ ์ž˜๋ชป ์•Œ๊ณ  ์žˆ๋Š”๊ฑด๊ฐ€...? ๊ทธ๋ฆฌ๊ณ  ์ œ์ถœํ•  ๋•Œ๋งˆ๋‹ค ์‹œ๊ฐ„๋„ ๋‹ฌ๋ผ์ง„๋‹ค. ์ฒ˜์Œ ๋‚ธ ๊ฒƒ๋ณด๋‹ค ๋Š๋ ค์ง€๊ธฐ๋„ ํ•˜๊ณ  ๋นจ๋ผ์ง€๊ธฐ๋„ ํ•˜๊ณ  ๋ญ์ง€..?

728x90
๋ฐ˜์‘ํ˜•