zoukankan      html  css  js  c++  java
  • 动态规划算法-3

    挖金矿(背包问题)

        /**
         * RUN THIS
         */
        public static void main(String[] args) {
            System.out.println(d());
        }
    
        public static int d() {
            int[] person = {5, 5, 3, 4, 3};
            int[] gold = {400, 500, 200, 300, 350};
            int personCount = 10;
            int m = gold.length;
            int n = personCount;
            int[][] dp = new int[m][n];
            //推导公式
            //      挖最后一个矿:f(金矿数,总人数)=f(金矿数,总人数-person[n])+gold[n] ,解释:gold[n]为最后一个矿的金币数,person[n]为最后一个金矿需要的人数
            //      不挖最后一个矿:f(金矿数,总人数)=f(金矿数-1,总人数)
            //实际推到公式:f(金矿数,总人数)=Max( f(金矿数-1,总人数) , f(金矿数,总人数-person[n])+gold[n] )
    
            //初始化:为0的情况
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {//人数
                    int goldPerson = person[i];
                    int goldCount = gold[i];
                    if (goldPerson > (j + 1)) {
                        dp[i][j] = 0;
                    }
                    if ((j + 1) >= goldPerson) {
                        dp[i][j] = goldCount;
                    }
                }
            }
            print(dp);
    
            for (int i = 1; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (j >= person[i]) {
                        System.out.println("i=" + i + ";j=" + j + ";person[i]=" + person[i] + ";dp[i - 1][(j + 1) - person[i]]=" + dp[i - 1][j - person[i]]);
                        //推导公式
                        //      挖最后一个矿:f(金矿数,总人数)=f(金矿数,总人数-person[n])+gold[n] ,解释:gold[n]为最后一个矿的金币数,person[n]为最后一个金矿需要的人数
                        //      不挖最后一个矿:f(金矿数,总人数)=f(金矿数-1,总人数)
                        //实际推到公式:f(金矿数,总人数)=Max( f(金矿数-1,总人数) , f(金矿数,总人数-person[n])+gold[n] )
                        dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - person[i]] + gold[i]);
                    }
                }
                print(dp);
            }
            return dp[m - 1][n - 1];
        }
  • 相关阅读:
    (六)定时测量
    (五)内核同步
    (四)中断和异常
    smba
    (四)支持 Nand Flash
    (三) 支持Nor Flash
    Convolutional Neural Networks(5):Pooling Layer
    Convolutional Neural Networks(4):Feature map size,Padding and Stride
    Convolutional Neural Networks(3):Convolution and Channels
    Convolutional Neural Networks(2):Sparse Interactions, Receptive Field and Parameter Sharing
  • 原文地址:https://www.cnblogs.com/use-D/p/13285898.html
Copyright © 2011-2022 走看看