0
[待解决问题]

# include<algorithm>

using namespace std;

class Travling {
friend int TSP(int, int, int, int);
private:
void Backrack(int i);
int n;//顶点数
int
x;//当前解存放点序号
int* bestx;//当前最优解
int
a;//邻接矩阵
int cc;//当前费用
int bestc;//当前最优值
int NoEdge;//无边标记
};

void Travling::Backrack(int i) {
if (i == n) {
if (a[x[n - 1]][x[n]] != NoEdge && a[x[n]][1] != NoEdge && ((cc + a[x[n - 1]][x[n]] + a[x[n]][1] < bestc) || bestc == NoEdge)) {
for (auto j = 1; j <= n; j++)bestx[j] = x[j];
bestc = cc + a[x[n - 1]][x[n]] + a[x[n]][1];
}
}
else {
for (auto j = i; j <= n; j++)
//判断是否可以进入x[j]子树
if (a[x[i - 1]][x[j]] != NoEdge && ((cc + a[x[i - 1]][x[j]] < bestc) || bestc == NoEdge)) {
//搜索子树
swap(x[i], x[j]);
cc += a[x[i - 1]][x[i]];
Backrack(i + 1);
cc -= a[x[i - 1]][x[i]];
swap(x[i], x[j]);
}
}
}

int TSP(int** a, int* v, int n, int NoEdge) {
Travling Y;
Y.x = new int[n + 1];
for (auto i = 0; i <= n; i++)
Y.x[i] = i;
Y, a = a;
Y.n = n;
Y.bestc = NoEdge;
Y.cc = 0;
Y.bestx = new int[n+1];
Y.NoEdge = NoEdge;
Y.Backrack(2);
v = Y.bestx;
delete[]Y.x;
delete[]Y.bestx;
return Y.bestc;
}
int main()
{
int n;
int sum = 0;
cin >> n;
int maxint = 9999;
int** a = new int* [n + 1];
int* v = new int[n + 1];
for (auto i = 0; i <= n; i++)
a[i] = new int[n + 1];
for (auto i = 1; i <= n; i++)
for (auto j = 1; j <= n; j++) {
cin >> a[i][j];
if (a[i][j] == 0)a[i][j] = maxint;
}
sum = TSP(a, v, n, maxint);
cout << sum;
for (auto i = 1; i <= n; i++)
cout << v[i] << " ";

}

# endif

/*
4
0 30 6 4
30 0 5 10
6 5 0 20
4 10 20 0
*/

您需要登录以后才能回答，未注册用户请先注册