Java调用CPLEX解决TSP问题(基于DFJ模型)

DFJ模型易于理解,可拓展性强,但纯DFJ模型需要一次性求解节点的所有子集,需要用到回溯法,相对效率较低。当节点为n时,所需的子集合规模达2^n-2n-2个,具有指数级别复杂度。当节点个数为101个时,基本卡着不动了。

下面是Java调用CPLEX解决TSP问题的DFJ模型。这里较为精巧的是递归求解子集,在我另一篇博文中有所介绍,此处不再细解。博文链接如下:https://blog.csdn.net/u011561033/article/details/95493064

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import ilog.concert.*;
import ilog.concert.IloCopyManager.Check;
import ilog.cplex.*;

public class Main {
	public static int _cityNum;
	public static double[][] _cityDis;

	public static ArrayList _set;
	public static ArrayList> _setPool;

	public static ArrayList _setCG;// for constraint generation
	public static ArrayList> _setCGPool;// for constraint
															// generation

	public static long _time;
	public static double _ansLength;
	public static double[][] _ansCity;

	public static void main(String[] args) {
		
		String filename = "E:\\JAVA\\TSP1\\data\\gr120.tsp";
		// 读取标准化后的文件
		ReadData(filename);
		// 运行算法
		 DFJsolve();// DFJ方法
		// 输出结果
		WriteAns(filename + ".ans");
		// 检查是否满足约束
		// checkOpt();
		System.out.println("finish");
	}



	// DFJ方法解决
	public static void DFJsolve() {
		try {
			_ansCity = new double[_cityNum][_cityNum];

			IloCplex cplex = new IloCplex();
			IloIntVar[][] x = new IloIntVar[_cityNum][_cityNum];// 0-1变量

			// 设定变量取值范围
			for (int i = 0; i < _cityNum; i++) {
				for (int j = 0; j < _cityNum; j++) {
					if (i != j)
						x[i][j] = cplex.intVar(0, 1);
					else
						x[i][j] = cplex.intVar(0, 0);
				}
			}
			// 目标函数
			IloLinearNumExpr tempObj = cplex.linearNumExpr();
			for (int i = 0; i < _cityNum; i++) {
				tempObj.add(cplex.scalProd(x[i], _cityDis[i]));
			}
			cplex.addMinimize(tempObj);

			// 添加约束 1 和 2
			for (int i = 0; i < _cityNum; i++) {
				IloLinearIntExpr constraint2 = cplex.linearIntExpr();
				for (int j = 0; j < _cityNum; j++) {
					constraint2.addTerm(x[j][i], 1);
				}
				cplex.addEq(cplex.sum(x[i]), 1);
				cplex.addEq(constraint2, 1);
			}

			// 添加约束 3
			// 设置点的子集,个数从2到n-2
			for (int size = 2; size <= _cityNum - 2; size++) {
				SubSet(size);
				System.out.println(size + "点子集求解完毕,一共" + _setPool.size() + "个集合");
				while (!_setPool.isEmpty()) {
					_set = _setPool.get(0);
					IloLinearNumExpr expression = cplex.linearNumExpr();
					for (int i = 0; i < _set.size(); i++)
						for (int j = i + 1; j < _set.size(); j++) {
							expression.addTerm(1, x[_set.get(i) - 1][_set.get(j) - 1]);
							expression.addTerm(1, x[_set.get(j) - 1][_set.get(i) - 1]);// imp
						}
					cplex.addLe(expression, _set.size() - 1);
					_setPool.remove(0);
				}
			}
			// 输出结果
			long start = System.currentTimeMillis();
			boolean success = cplex.solve();
			long end = System.currentTimeMillis();
			_time = end - start;

			if (success) {
				_ansLength = cplex.getObjValue();
				for (int i = 0; i < _cityNum; i++)
					_ansCity[i] = cplex.getValues(x[i]);
			} else
				System.out.println("cplex.solve() failed.");

		} catch (IloException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 设置点的子集
	public static void SubSet(int size) {
		_setPool = new ArrayList>();
		_set = new ArrayList<>();
		DoSubSet(1, 0, size);
	}

	// 递归求解子集
	public static void DoSubSet(int cur, int cnt, int size) {
		if (cnt == size) {
			_setPool.add(new ArrayList<>(_set));
			return;
		}
		for (int i = cur; i <= _cityNum; i++) {
			_set.add(i);
			DoSubSet(i + 1, cnt + 1, size);
			_set.remove(_set.size() - 1);
		}
	}


	// 检查是否满足条件 绕圈走一遍
	public static boolean checkOpt() {
		System.out.println("check\n--------------");
		_setCGPool = new ArrayList>();
		boolean[] flag = new boolean[_cityNum];
		for (int i = 0; i < _cityNum; i++) {
			if (flag[i])
				continue;
			_setCG = new ArrayList();
			int st = i;
			int cnt = 0;
			System.out.println("\n");
			while (true) {
				System.out.print(st + " ");
				_setCG.add(st);
				flag[st] = true;
				for (int j = 0; j < _cityNum; j++) {
					if ((int) (_ansCity[st][j] + 0.00001) == 1) {
						st = j;
						break;
					}
				}
				cnt++;
				if (st == i || cnt >= _cityNum)
					break;
			}
			_setCGPool.add(new ArrayList(_setCG));
		}
		if (_setCGPool.size() == 1) {
			System.out.println("\nsuccess");
			return true;
		} else {
			System.out.println("\nfail");
			return false;
		}
	}

	// 输出答案
	public static void WriteAns(String filename) {
		System.out.print(filename + "\n------------------------------\n");
		System.out.printf("rum time(sec)= %-10.2f\n", _time / 1000.0);
		System.out.printf("min= %-10.2f\n", _ansLength);
		for (int i = 0; i < _cityNum; i++) {
			for (int j = 0; j < _cityNum; j++)
				System.out.print((int) (_ansCity[i][j] + 0.00001) + " ");
			System.out.println();
		}
	}

	// 读取标准化后的数据
	public static void ReadData(String filename) {
		File file = new File(filename);
		BufferedReader reader = null;
		try {
			System.out.println("正在读取" + filename);
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			tempString = reader.readLine();
			_cityNum = Integer.parseInt(tempString.trim());
			_cityDis = new double[_cityNum][_cityNum];
			for (int i = 0; i < _cityNum; i++) {
				tempString = reader.readLine();
				String[] arg = tempString.split(" ");
				for (int j = 0; j < arg.length; j++) {
					_cityDis[i][j] = Double.parseDouble(arg[j]);
					_cityDis[j][i] = _cityDis[i][j];
				}
			}

			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}
}

 

你可能感兴趣的:(CPLEX,Java,运筹学)