01背包Java代码

来源:互联网 发布:云计算产业孵化器 编辑:程序博客网 时间:2024/06/15 02:59
import java.util.Scanner;public class Application {  public static void main(String[] args){    Scanner scanner = new Scanner(System.in);    int v = scanner.nextInt(); // 背包容量    int numOfgoods = scanner.nextInt();    int[] cost = new int[numOfgoods];    int[] value = new int[numOfgoods];    for(int i =0;i<numOfgoods;i++){      cost[i] = scanner.nextInt(); //物品重量 eg: 2 3 4 5 1    }    for(int i =0;i<numOfgoods;i++){      value[i] = scanner.nextInt(); //物品价值 eg: 5 6 3 7 2    }    zeroonepack(v,cost,value);  }  public static void zeroonepack(int v, int[] costs,int[] values){    int[] f = new int[v+1];    for(int i=0,items =costs.length;i< items;i++){      for(int j=v;j>=0;j--){        if(j>=costs[i])          f[j] = Integer.max(f[j],f[j-costs[i]]+values[i]);      }    }    System.out.print(f[v]);  }}