File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ // 평범한 배낭
2+ // https://www.acmicpc.net/problem/12865
3+
4+ const fs = require ( 'fs' ) ;
5+ const stdin = ( process . platform === 'linux'
6+ ? fs . readFileSync ( '/dev/stdin' ) . toString ( ) . trim ( )
7+ : `4 7
8+ 6 13
9+ 4 8
10+ 3 6
11+ 5 12`
12+ ) . split ( '\n' ) ;
13+
14+ const input = ( ( ) => {
15+ let line = 0 ;
16+ return ( ) => stdin [ line ++ ] ;
17+ } ) ( ) ;
18+
19+ const [ N , K ] = input ( )
20+ . split ( ' ' )
21+ . map ( ( each ) => parseInt ( each ) ) ;
22+
23+ const arr = [ [ 0 , 0 ] ] ;
24+
25+ for ( let i = 0 ; i < N ; i ++ ) {
26+ arr . push (
27+ input ( )
28+ . split ( ' ' )
29+ . map ( ( each ) => parseInt ( each ) )
30+ ) ;
31+ }
32+
33+ const dp = Array . from ( Array ( N + 1 ) , ( ) => Array ( K + 1 ) . fill ( 0 ) ) ;
34+
35+ for ( let i = 1 ; i <= N ; i ++ ) {
36+ const weight = arr [ i ] [ 0 ] ;
37+ const value = arr [ i ] [ 1 ] ;
38+
39+ for ( let j = 1 ; j <= K ; j ++ ) {
40+ if ( j >= weight ) {
41+ dp [ i ] [ j ] = Math . max ( dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ j - weight ] + value ) ;
42+ continue ;
43+ }
44+ dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ;
45+ }
46+ }
47+
48+ console . log ( dp [ N ] [ K ] ) ;
49+
50+ /*
51+
52+ ## How
53+ 유명한 DP 문제이다. 조건에 맞게 점화식을 잘 세우면 된다.
54+
55+ N x K 배열을 만들어서 각 물건의 무게에 따른 가치를 메모이지이 션 하여 채워나간다.
56+
57+ 점화식에 해당하는 수도 코드는 아래와 같다.
58+
59+ if j <= weight:
60+ dp[i][j] = Max((dp[i][j - weight] + value), dp[i - 1][j]) # 무게만큼 뺀 위치의 가치 + 현재 가치 vs 이전 물품 최댓값
61+ else:
62+ dp[i][j] = dp[i - 1][j] # 이전 물품 최댓값
63+
64+ 이를 코드로 옮기면 배낭에 넣을 수 있는 가치의 최댓값을 구할 수 있다.
65+
66+ ## Retrospective
67+
68+ */
You can’t perform that action at this time.
0 commit comments