File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
minjeong/DynamicProgramming Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+ input = sys .stdin .readline
3+
4+ # 1. 입력
5+ N = int (input ())
6+ MOD = 10 ** 9
7+
8+
9+ # 2. DP 정의
10+ # dp[n][last_digit][bitmask]
11+ # n: 숫자 길이, last_digit: 마지막 자리 숫자, bitmask: 지금까지 어떤 숫자들이 나왔는지 (비트마스크)
12+ # 범위 - n: 입력값, last_digit: 0~9, bitmask: 0~1023
13+ dp = [[[0 for _ in range (1024 )] for _ in range (10 )] for _ in range (N + 1 )]
14+
15+ # 3. 초기상태 설정
16+ # 길이가 1일 때, 0을 제외하고 1~9로 시작할 수 있음
17+ for i in range (1 , 10 ):
18+ dp [1 ][i ][1 << i ] = 1
19+
20+ # 4. 점화식대로 DP 채우기
21+ # n: N번째 수
22+ for n in range (2 , N + 1 ):
23+ # last_digit: 마지막 자리 숫자
24+ for last_digit in range (10 ):
25+ # 0~9까지 모든 수를 방문해야 한다는 조건이 있으므로 방문여부를 비트마스킹을 통해 저장
26+ for mask in range (1024 ):
27+ if last_digit == 0 :
28+ dp [n ][last_digit ][mask | (1 << last_digit )] += dp [n - 1 ][last_digit + 1 ][mask ]
29+ elif last_digit == 9 :
30+ dp [n ][last_digit ][mask | (1 << last_digit )] += dp [n - 1 ][last_digit - 1 ][mask ]
31+ else :
32+ dp [n ][last_digit ][mask | (1 << last_digit )] += (
33+ dp [n - 1 ][last_digit - 1 ][mask ] + dp [n - 1 ][last_digit + 1 ][mask ]
34+ )
35+ dp [n ][last_digit ][mask | (1 << last_digit )] %= MOD
36+
37+ # 5. 정답 계산 및 출력
38+ answer = 0
39+ for i in range (10 ):
40+ # N자리 수 중에서 i로 끝나는 수 중 0부터 9까지 다 있는 수를 누적해서 더하기
41+ answer += dp [N ][i ][1023 ]
42+
43+ print (answer % MOD )
You can’t perform that action at this time.
0 commit comments