-
Notifications
You must be signed in to change notification settings - Fork 2
/
BranchAndBound.java
91 lines (77 loc) · 3.1 KB
/
BranchAndBound.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
import java.io.*;
/**
* Best First Branch and Bound Algorithm for the 0/1 Knapsack problem.
* This algorithm uses Lagrangian relaxation to prune the Branch and Bound tree.
* @author Shalin Shah
* Email: shalin@alumni.usc.edu
*/
public class BranchAndBound
{
public static void main(String [] args)
{
long start = System.currentTimeMillis();
LagrangianRelaxation.calculateLambda();
KNode incumbent = GreedySolution.runGreedyAlgorithm();
System.out.println("Greedy Solution - " + incumbent.value());
incumbent = RandomSearch.randomSearch(incumbent);
System.out.println("Improved Greedy Solution - " + incumbent.value());
incumbent = runBranchAndBound(incumbent);
long end = System.currentTimeMillis();
System.out.println((end-start) + " milliseconds.");
System.out.println("Optimum Value: " + incumbent.value());
System.out.println("Weight: " + incumbent.weight());
System.out.println(incumbent.getKnapsackContents());
}
public static KNode runBranchAndBound(KNode in)
{
KNode incumbent = new KNode((BitSet)in.getKnapsackContents().clone(), 0, in.weight(), in.value());
TreeSet heap = new TreeSet();
KNode node1 = new KNode(new BitSet(Constants.NUMBER_OBJECTS), 0, 0, 0);
KNode node2 = new KNode(new BitSet(Constants.NUMBER_OBJECTS), 0, 0, 0);
node1.addOne();
node2.addZero();
if(node1.maxValue() > incumbent.value())
heap.add(node1);
if(node2.maxValue() > incumbent.value())
heap.add(node2);
boolean heapEmpty = false;
while(!heap.isEmpty())
{
KNode node = (KNode)heap.first();
heap.remove(node);
while(node.getIndex() == Constants.NUMBER_OBJECTS)
{
node.fathom();
if(node.value() > incumbent.value() && Util.isValidSolution(node))
{
incumbent = node;
}
if(!heap.isEmpty())
{
node = (KNode)heap.first();
heap.remove(node);
}
else
{
heapEmpty = true;
break;
}
}
if(heapEmpty)
{
break;
}
/* Expand the node */
KNode node3 = new KNode((BitSet)node.getKnapsackContents().clone(), node.getIndex(), node.weight(), node.value());
KNode node4 = new KNode((BitSet)node.getKnapsackContents().clone(), node.getIndex(), node.weight(), node.value());
node3.addOne();
node4.addZero();
if(node3.maxValue() > incumbent.value() && Util.isValidSolution(node3))
heap.add(node3);
if(node4.maxValue() > incumbent.value() && Util.isValidSolution(node4))
heap.add(node4);
}
return incumbent;
}
}