(Java实现) 装载问题

2.装载问题
【问题描述】
有一批共n个集装箱要装上艘载重量为c的轮船,其中集装箱i的重量为wi。找出一种最优装载方案,将轮船尽可能装满,即在装载体积不受限制的情况下,将尽可能重的集装箱装上轮船。
【输入格式】
由文件load.in给出输入数据。第一行有2个正整数n和c。n是集装箱数,c是轮船的载重量。接下来的1行中有n个正整数,表示集装箱的重量。
【输出格式】
将计算出的最大装载重量输出到文件load.out。
【输入样例】
5 10
7 2 6 5 4
【输出样例】
10


import java.util.Scanner;


public class zhuangzaiwenti {
	public static int [] num;
	public static boolean [] bool;
	public static int sum=0,min = Integer.MAX_VALUE,c,temp=0;
	public static void main(String[] args) {
		Scanner sc =new Scanner(System.in);
		int n = sc.nextInt();
		 c = sc.nextInt();
		num = new int [n+1];
		bool = new boolean [n+1];
		for (int i = 1; i <=n; i++) {
			num[i]=sc.nextInt();
		}
		f(0);
		System.out.println(temp);
	}
	public static void f(int sum){
		if(Math.abs(c-sum)<min){
			min=c-sum;
			temp=sum;
			
		}
		for (int i = 1; i <num.length; i++) {
			if(!bool[i]){
				bool[i]=true;
				f(sum+num[i]);
				bool[i]=false;
			}
		}
	}

}

原文地址:https://www.cnblogs.com/a1439775520/p/12948875.html