tsp贪心法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值