其实精确算法也好,启发式算法也好,都是独立的算法,可以不依赖求解器进行代码实现的,只要过程符合算法框架即可。只不过平常看到的大部分是精确算法在各种整数规划模型上的应用,为此难免脱离不了cplex等求解器。下面我们用分支定界算法求解TSP问题的代码实现,完全脱离求解器。
代码框架如下
Timer类:计时用
package tspsolver;
public class Timer
{
private long startTime;
private long stopTime;
private boolean running;
private final double nano = 1000000000.0;
public Timer()
{
super();
}
public void reset()
{
this.startTime = 0;
this.running = false;
}
public void start()
{
this.startTime = System.nanoTime();
this.running = true;
}
public void stop()
{
if (running)
{
this.stopTime = System.nanoTime();
this.running = false;
}
}
public double getTime()
{
double elapsed;
if (running)
{
elapsed = ((System.nanoTime() - startTime) / nano);
}
else
{
elapsed = ((stopTime - startTime) / nano);
}
return elapsed;
}
}
TSPInstanceReader类:读取实例
package tspsolver;
import java.awt.GraphicsEnvironment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class TSPInstanceReader {
ArrayList<City> cities;
double[][] distanceMatrix;
public TSPInstanceReader(String instanceFile) {
File file;
if(instanceFile != null) {
file = new File(instanceFile);
}
else {
JFileChooser chooser = new JFileChooser();
int response = chooser.showOpenDialog(null);
if(response != JFileChooser.APPROVE_OPTION)
return;
file = chooser.getSelectedFile();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
}
catch(IOException e) {
alert("Error loading file " + e);
System.exit(1);
}
int dimension = 0;
try {
String line;
while(!(line = reader.readLine()).equals("NODE_COORD_SECTION")) {
String[] entry = line.split(":");
//System.out.println(entry[0].trim());
switch(entry[0].trim()) {
case "TYPE":
if(!entry[1].trim().equals("TSP"))
throw new Exception("File not in TSP format");
break;
case "DIMENSION":
dimension = Integer.parseInt(entry[1].trim());
break;
}
}
}
catch(Exception e) {
alert("Error parsing header " + e);
System.exit(1);
}
System.out.println("DIMENSION = "+dimension);
this.cities = new ArrayList<City>(dimension);
try {
String line;
// while((line = reader.readLine()) != null && !line.trim().equals("EOF")) {
// String[] entry = line.