#include <iostream>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <fstream>
#include <iomanip> // 本文用于输出对齐
using namespace std;
const int max_vexNum = 20;
bool is_visited[max_vexNum];
int path_num = 0;
int bestLength = 10000000;
int path_index = 0;
int path_DFS[max_vexNum][max_vexNum];
double lenth_DFS[max_vexNum];
typedef struct {
int vex_num, arc_num; // 顶点数 边数
double arcs[max_vexNum][max_vexNum]; // 邻接矩阵
}Graph;
void TspTanxin(Graph G, int city_start) {
int edgeCount = 0, TSPLength = 0;
int min, u, v;
u = city_start; is_visited[city_start] = true;
while (edgeCount < G.arc_num-1 ) {
min = 100;
for (int j = 0; j < G.arc_num; j++) {
if (!is_visited[j] && (G.arcs[u][j] >0) && G.arcs[u][j] < min) {
v = j; min = G.arcs[u][j];
}
}
TSPLength+= G.arcs[u][v];
is_visited[v] = true; edgeCount++;
cout << u << "->" << v << endl;
u = v;
}
cout << v << "->" << city_start << endl;
TSPLength += G.arcs[u][city_start];
if (TSPLength < bestLength)
bestLength = TSPLength;
}
int main() {
Graph G ;
cout << "tsp问题蛮力法..." << endl;
cout << "多少个城市:" << endl;
cin >> G.vex_num;
cout << "多少条路径" << endl;
cin >> G.arc_num;
cout << "路径起点终点,路径长度" << endl;
for (int i = 0; i < G.arc_num; i++) {
int a, b, c;
cin >> a >> b >> c;
G.arcs[a][b] = c;
G.arcs[b][a] = c;
G.arcs[i][i] = 0;
}
for (int i = 0; i < G.vex_num; i++)
{
for (int j = 0; j< G.vex_num; j++)
cout << G.arcs[i][j] << " ";
cout<< endl;
}
for (int i = 0; i < G.vex_num; i++)
{
is_visited[i] = false;
}
cout << "开始城市是-0" << endl;
int city_start=0;
time_t T_begin = clock();
//DFS(G, city_start);
TspTanxin(G, city_start);
// DFS_fout<<"最短路程bestLength = "<<bestLength<<endl;
cout << "最短路程bestLength = " << bestLength << endl;
time_t T_end = clock();
double RunningTime = double(T_end - T_begin) / CLOCKS_PER_SEC;
// DFS_fout<<"程序运行时间 RunningTime = "<<RunningTime<<endl;
cout << "程序运行时间 RunningTime = " << RunningTime << endl;
system("pause");
return 0;
}