以下是一个简单的C++程序,使用蛮力法解决旅行商问题,并从文件中读取图信息:

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

const int INF = 0x3f3f3f3f;

int n; // 城市数量
vector<vector<int>> graph; // 图
vector<int> path; // 当前路径
vector<bool> visited; // 记录是否已经访问过该城市
int ans = INF; // 最短路径长度

void dfs(int cur, int len) {
    if (len >= ans) return; // 剪枝
    if (path.size() == n) { // 所有城市都已经访问过
        ans = min(ans, len + graph[cur][0]); // 更新最短路径长度
        return;
    }
    for (int i = 1; i < n; i++) {
        if (!visited[i]) {
            visited[i] = true;
            path.push_back(i);
            dfs(i, len + graph[cur][i]);
            path.pop_back();
            visited[i] = false;
        }
    }
}

int main() {
    ifstream fin("graph.txt"); // 打开文件
    fin >> n; // 读取城市数量
    graph = vector<vector<int>>(n, vector<int>(n));
    visited = vector<bool>(n, false);
    path.push_back(0); // 从第一个城市出发
    visited[0] = true;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            fin >> graph[i][j]; // 读取图信息
        }
    }
    fin.close(); // 关闭文件
    dfs(0, 0); // 从第一个城市开始搜索
    cout << "最短路径长度为:" << ans << endl;
    return 0;
}

假设图信息存储在文件graph.txt中,文件格式如下:

5
0 2 1 4 5
2 0 4 3 6
1 4 0 2 3
4 3 2 0 1
5 6 3 1 0

第一行为城市数量,接下来每行为一个城市到其他城市的距离。程序会从文件中读取这些信息,构造出图,并使用蛮力法求解最短路径长度


原文地址: https://www.cveoy.top/t/topic/faPQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录