![[백준 / BOJ] 11051번 이항 계수 2 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FxRfwm%2FbtrJqrfzKYF%2FvN8B0UuDQ1iH0VKf6DyeEk%2Fimg.png)
[백준 / BOJ] 11051번 이항 계수 2 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 6. 10. 20:41
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/11051
11051번: 이항 계수 2
첫째 줄에 \(N\)과 \(K\)가 주어진다. (1 ≤ \(N\) ≤ 1,000, 0 ≤ \(K\) ≤ \(N\))
www.acmicpc.net
문제

문제 풀이
그냥 풀면 N, K가 제한이 1000이므로 시간초과가 나는 문제이다. DP를 활용해야 하는 문제인데, 동적 계획법 파트에 있었으면 좋았을 것 같은 문제다.
이항 계수의 점화식은 아래 사진과 같다.

여기서 dp[1][1], dp[1][0]은 미리 1로 초기화해 주고 시작하면 된다.
파이썬은 바로 % 10007해도 괜찮다. 내장 함수의 힘인 것 같다.
C++ 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
int dp[1001][1001]; | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int N, K; | |
std::cin >> N >> K; | |
dp[1][1] = 1; | |
dp[1][0] = 1; | |
for (int i = 2; i <= N; ++i) { | |
for (int j = 0; j <= K; ++j) { | |
if (j == 0 || i == j) { | |
dp[i][j] = 1; | |
} | |
else { | |
// 매 연산마다 나눠주지 않으면 메모리 초과 | |
dp[i][j] = dp[i - 1][j - 1] % 10007 + dp[i - 1][j] % 10007; | |
} | |
} | |
} | |
std::cout << dp[N][K] % 10007; | |
return 0; | |
} |
Python 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import math | |
input = sys.stdin.readline | |
N, K = map(int, input().split()) | |
print(math.comb(N, K) % 10007) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 9375번 패션왕 신해빈 (C++, Python) (0) | 2022.06.12 |
---|---|
[백준 / BOJ] 1010번 다리 놓기 (C++, Python) (0) | 2022.06.12 |
[백준 / BOJ] 11050번 이항 계수 1 (C++, Python) (0) | 2022.06.10 |
[백준 / BOJ] 3036번 링 (C++, Python) (0) | 2022.06.09 |
[백준 / BOJ] 2981번 검문 (C++, Python) (0) | 2022.06.09 |
@Reo :: 코드 아카이브
자기계발 블로그