#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
// 生成随机图,返回二维数组表示城市间距离矩阵
std::vector<std::vector<int> > generateRandomGraph(int numCities) {
std::vector<std::vector<int> > graph(numCities, std::vector<int>(numCities, 0));
for (int i = 0; i < numCities; ++i) {
for (int j = 0; j < numCities; ++j) {
if (i != j) {
graph[i][j] = rand() % 100 + 1;
}
}
}
return graph;
}
// 贪心算法求解TSP路径成本
int greedyTSP(const std::vector<std::vector<int> >& graph, int startCity) {
int numCities = graph.size();
std::vector<bool> visited(numCities, false);
visited[startCity] = true;
int currentCity = startCity;
int totalCost = 0;
for (int i = 1; i < numCities; ++i) {
int minDistance = INT_MAX;
int nextCity = -1;
for (int j = 0; j < numCities; ++j) {
if (!visited[j] && graph[currentCity][j] < minDistance) {
minDistance = graph[currentCity][j];
nextCity = j;
}
}
visited[nextCity] = true;
totalCost += minDistance;
currentCity = nextCity;
}
totalCost += graph[currentCity][startCity];
return totalCost;
}
int main() {
srand(static_cast<unsigned int>(time(NULL)));
int numCities = 5; // 可按需修改城市数量
std::vector<std::vector<int> > graph = generateRandomGraph(numCities);
int startCity = rand() % numCities; // 随机选起始城市
int pathCost = greedyTSP(graph, startCity);
std::cout << "旅行商路径成本: " << pathCost << std::endl;
return 0;
}