Java装载问题队列式分枝限界法

最近在书上看到有关装载问题的分支限界法,总感觉代码有问题,于是用java敲了一波

import java.util.LinkedList;
import java.util.Queue;

public class Loading {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(maxLoading(new int[] { 40, 40, 10 }, 50));
	}

	public static int maxLoading(int[] w, int c) {
		Queue<Integer> queue = new LinkedList<>();
		int i = 0, max = 0;
		queue.add(0);
		while (true) {
			int flag = queue.remove();
			if (flag == -1) {
				if (queue.isEmpty()) {
					return max;
				}
				queue.add(-1);
				i++;
			} else {
				if (i == w.length) {
					if (flag > max) {
						max = flag;
					}
				} else {
					if (flag + w[i] <= c) {
						queue.add(flag + w[i]);
					}
					queue.add(flag);
					if (i == 0) {
						queue.add(-1);
						i++;
					}
				}
			}
		}

	}
}
一开始进入队列的0只是一个引子,每一层之间是用-1来间隔的,在i=0时因为前面没有-1,需要手动把这一层的-1加入队列形成间隔。两次入队所代表的就是选w[i]和不选,选择时就要判断会不会超过承载量c,不选时当然就可以直接入队了。


猜你喜欢

转载自blog.csdn.net/cool_jia/article/details/79113888