//......................h
#include <vector>
struct State
{
int curCity;//当前所在城市
int nextCity;//下一个要去的城市
vector <int> toPass;//未经过的城市
float cost;
};
#define MAXFLOAT 10000;
void TSP (float **, int);
void Initial (State &myState, int n);
void PrintState (State &myState);
float GetCostMin (State &myState, int curCity, float **C, int &deep);
float** ReadData (int &size);
void Retreat (State &myState, int setp);
void AddLast (int *steps, int size);
//....................cpp
void Initial(State &myState, int n) {
myState.curCity = 0;
myState.cost = MAXFLOAT;
for (int i = 1; i < n; i++)
myState.toPass.push_back(i);
}
void TSP(float **C, int MatrixSize) {
State myState;
memset(&myState, 0, sizeof(State));
Initial(myState, MatrixSize);
int *steps = new int[MatrixSize];
steps[0] = 0;
memset(steps, 0, sizeof(int) * MatrixSize);
for (int i = 1; i < MatrixSize; i++) {
GetCostMin(myState, myState.curCity, C, i);
steps[i] = myState.nextCity;
Retreat(myState, i);
}
AddLast(steps, MatrixSize);
for (int i = 0; i < MatrixSize; i++)
cout << steps[i] << " ";
}
void AddLast (int *steps, int size)
{
int *tmp = new int[size];
for (int i = 0; i < size; i++)
tmp[steps[i]] = 1;
for (int i = 0; i < size; i++)
if (tmp[i] != 1)
steps[size - 1] = i;
}
void Retreat(State &myState, int step) {
for (size_t i = 0; i < myState.toPass.size(); i++) {
if (myState.toPass[i] == myState.nextCity)
myState.toPass.erase(myState.toPass.begin() + i);
}
}
float GetCostMin(State &myState, int curCity, float **C, int &deep) {
float minCost = MAXFLOAT;
float cost;
myState.curCity = curCity;
if (myState.toPass.size() == 1) {
return C[myState.toPass[0]][0] + C[myState.curCity][myState.toPass[0]];
}
//递归求解
//for (int index = 1; index < 4;index++)
for (size_t i = 0; i < myState.toPass.size(); i++) {
State tmp = myState;
tmp.toPass.erase(tmp.toPass.begin() + i);
cost = C[curCity][myState.toPass[i]] + GetCostMin(tmp,
myState.toPass[i], C, deep);
if (minCost > cost) {
minCost = cost;
myState.nextCity = myState.toPass[i];
}
}
return minCost;
}
void PrintState(State &myState) {
cout << "in mystate*********" << endl;
int size = myState.toPass.size();
for (int i = 0; i < size; i++)
cout << myState.toPass[i] << " ";
cout << endl << myState.curCity << endl;
}
float ** ReadData(int &size) {
ifstream file("data");
if (!file) {
cout << "read error" << endl;
return NULL;
}
file >> size;
float **C = new float *[size];
for (int i = 0; i < size; i++)
C[i] = new float[size];
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
file >> C[i][j];
file.close();
return C;
}
完善中。。。。。。。。。。。