knapsack problem

Time:2022-8-16

package pack;

import java.util.Arrays;

public class KnapSack {
    public static int getMax01(int[] b, int[] w, int total){
        int[][] mem = new int[b.length+1][total+1];
        for(int i=1;i<=b.length;i++){
            for(int j=1;j<=total;j++){
                mem[i][j] = mem[i-1][j];
                if(w[i-1]<=j) mem[i][j] = Math.max(mem[i][j], mem[i-1][j-w[i-1]]+b[i-1]);
            }
        }
        return mem[b.length][total];
    }
    public static int getMax01Optimize(int[] b, int[] w, int total){
        int[] mem = new int[total+1];
        for(int i=1;i<=b.length;i++){
            for(int j=total;j>=1;j--){
                mem[j] = mem[j];
                if(w[i-1]<=j)
                    mem[j] = Math.max(mem[j], mem[j-w[i-1]]+b[i-1]);
            }
            System.out.println(Arrays.toString(mem));
        }
        return mem[total];
    }public static void main(String[] args) {
//        System.out.println(getMax(new int[]{1,2,4,2,5},new int[]{1,2,3,2,5},10));
        System.out.println(getMax01Optimize(new int[]{1,2,4,2,5},new int[]{1,2,3,2,5},10));
        System.out.println(getMaxAllPackOptimize(new int[]{1,2,4,2,5},new int[]{1,2,3,2,5},10));
    }
}

 

 

package pack;

import java.util.Arrays;

public class KnapSack {

    public static int getMaxAllPack(int[] b, int[] w, int total){
        int[][] mem = new int[b.length+1][total+1];
        for(int i=1;i<=b.length;i++){
            for(int j=1;j<=total;j++){
                mem[i][j] = mem[i-1][j];
                if(w[i-1]<=j) mem[i][j] = Math.max(mem[i][j], mem[i][j-w[i-1]]+b[i-1]);
            }
        }
        return mem[b.length][total];
    }

    public static int getMaxAllPackOptimize(int[] b, int[] w, int total){
        int[] mem = new int[total+1];
        for(int i=1;i<=b.length;i++){
            for(int j=1;j<=total;j++){
                if(w[i-1]<=j) mem[j] = Math.max(mem[j], mem[j-w[i-1]]+b[i-1]);
            }
        }
        return mem[total];
    }

    public static void main(String[] args) {
        System.out.println(getMaxAllPackOptimize(new int[]{1,2,4,2,5},new int[]{1,2,3,2,5},10));
    }
}

 

Recommended Today

Implementation example of c# shielding shortcut keys

Table of contents foreword principle accomplish 1. Program class 2. Form1 class 3. Declare the windows api PS: foreword Sometimes the development will encounter such a demand, the software needs to shield the user's combination shortcut keys or certain keys, to avoid forcibly exiting the software, to prevent do not operate and so on. principle […]