我cplex
用来解决旅行商问题(TSP)。鉴于如果x[i][j]=1
,则路径从城市i到城市j,否则,这些城市之间没有路径。对应的矩阵:
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
完成cplex
求解后,我想得到这样的值x
:
if(cplex.solve()){
double[][] var = new double[n][n];
for(int i = 0; i<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
var[i][j] = cplex.getValue(x[i][j]);
if(var[i][j] ==1){
System.out.print(i + " "+ j);
}
}
}
}
但它给出了一个错误。我会感谢任何可以提供一些建议的人。错误在:
var[i][j] = cplex.getValue(x[i][j]);
解释是:
Exception in thread "main" ilog.cplex.IloCplex$UnknownObjectException: CPLEX Error: object is unknown to IloCplex
at ilog.cplex.IloCplex.getValue(IloCplex.java:6495)
整个代码如下:
import java.io.IOException;
import ilog.concert.*;
import ilog.cplex.IloCplex;
public class TSP {
public static void solveMe(int n) throws IloException, IOException{
//random data
double[] xPos = new double[n];
double[] yPos = new double[n];
for (int i = 0; i < n; i ++){
xPos[i] = Math.random()*100;
yPos[i] = Math.random()*100;
}
double[][] c = new double[n][n];
for (int i = 0 ; i < n; i++){
for (int j = 0 ; j < n; j++)
c[i][j] = Math.sqrt(Math.pow(xPos[i]-xPos[j], 2)+ Math.pow(yPos[i]-yPos[j],2));
}
//model
IloCplex cplex = new IloCplex();
//variables
IloNumVar[][] x = new IloNumVar[n][];
for(int i = 0; i < n; i++){
x[i] = cplex.boolVarArray(n);
}
IloNumVar[] u = cplex.numVarArray(n, 0, Double.MAX_VALUE);
//Objective
IloLinearNumExpr obj = cplex.linearNumExpr();
for(int i =0 ; i <n ; i++){
for (int j = 0; j< n ;j++){
if(j != i){
obj.addTerm(c[i][j], x[i][j]);
}
}
}
cplex.addMinimize(obj);
//constraints
for(int j = 0; j < n; j++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int i = 0; i< n ; i++){
if(i!=j){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 0; i < n; i++){
IloLinearNumExpr expr = cplex.linearNumExpr();
for(int j = 0; j< n ; j++){
if(j!=i){
expr.addTerm(1.0, x[i][j]);
}
}
cplex.addEq(expr, 1.0);
}
for(int i = 1; i < n; i++){
for(int j = 1; j < n; j++){
if(i != j){
IloLinearNumExpr expr = cplex.linearNumExpr();
expr.addTerm(1.0, u[i]);
expr.addTerm(-1.0, u[j]);
expr.addTerm(n-1, x[i][j]);
cplex.addLe(expr, n-2);
}
}
}
//solve mode
if(cplex.solve()){
System.out.println();
System.out.println("Solution status = "+ cplex.getStatus());
System.out.println();
System.out.println("cost = " + cplex.getObjValue());
for(int i = 0; i<x.length; i++){
for(int j = 0 ; j < x[i].length; j ++){
System.out.print(cplex.getValue(x[i][j]));
}
}
}
//end
cplex.end();
}
}