旅行商贪心算法

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值