Created
December 7, 2013 14:42
-
-
Save inage/7843094 to your computer and use it in GitHub Desktop.
ナップサック問題その2
This file contains hidden or 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
| ## ナップサック問題その2 | |
| ## http://rubyfiddle.com/riddles/5c02c | |
| n = 4 | |
| w = [2,1,3,2] | |
| v = [3,2,4,2] | |
| W = 5 | |
| res =0 | |
| INF = 1000000 | |
| dp = Array.new(n+1,INF).map{Array.new(n*n+1,INF)} | |
| j=0 | |
| dp[0][0] = 0 | |
| n.times{|i| | |
| (n*n).times {|j| | |
| if j < v[i] | |
| dp[i+1][j] = dp[i][j] | |
| else | |
| dp[i+1][j] = [dp[i][j] , dp[i][j-v[i]]+w[i]].min | |
| end | |
| } | |
| } | |
| i = 0 | |
| while i <= n*n | |
| if dp[n][i] <= W | |
| res = i | |
| end | |
| i += 1 | |
| end | |
| puts res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment