商人需要走遍每一个节点后回到起点。节点之间的权重为所需的成本。并不是所有的节点相互都可达。
如表所示,有5个节点,他们之间的权重如下图。找出商人的最小成本路线。(0代表不可达或不通)
节点 | 1 | 2 | 3 | 4 | 5 |
1 | 0 | 10 | 0 | 12 | 4 |
2 | 10 | 0 | 15 | 5 | 8 |
3 | 0 | 15 | 0 | 30 | 7 |
4 | 12 | 5 | 30 | 0 | 6 |
5 | 4 | 8 | 7 | 6 | 0 |
通过回溯算法全排列所有可能即可。
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
/*
输入数据结构
0,10,0,12,4
10,0,15,5,8
0,15,0,30,7
12,5,30,0,6
12,5,7,6,0
*/
//假设路径间的花费小等于0的时候,代表无关系
void swap(int* pre, int* post) {//交换数据
if (*pre == *post) {
return;
}
int temp = *pre;
*pre = *post;
*post = temp;
}
class Solution {
private:
vector<vector<int>> map;//记录路径之间的关系
int* path;//记录最优解
int* tempPath;//记录临时解
int tempCost;//记录临时花费
int minCost;//记录最低花销
int count;//记录节点数目
void backTrack(int node);//回溯算法
public:
Solution(const vector<vector<int>>& map, int count);
~Solution();
void SearchPath();
};
Solution::Solution(const vector<vector<int>>& map,int count) {
this->map = map;
tempCost = 0;
this->count = count;
minCost = INT_MAX;
tempPath = new int[count];
for (int i = 0;i < count;i++) {//记录初始化节点
tempPath[i] = i;
}
path = new int[count];
}
Solution::~Solution() {
delete[] path;
delete[] tempPath;
}
void Solution::backTrack(int node) {
if (node == count - 1) {//如果已经是最后的节点
if (map[tempPath[node]][0] != 0 && //本节点与第一个节点间有路
map[tempPath[node - 1]][tempPath[node]] != 0 &&//本节点与前一个节点间有路
tempCost + map[tempPath[node]][0] + map[tempPath[node - 1]][tempPath[node]] < minCost) {//当前结果小于我们已有的结果
minCost = tempCost + map[tempPath[node]][0] + map[tempPath[node - 1]][tempPath[node]];//记录最小花费
for (int i = 0;i < count;i++) {
path[i] = tempPath[i];//更新路径
}
}
return;
}
else {
for (int i = node;i < count;i++) {
if (map[tempPath[node - 1]][tempPath[i]] != 0 &&//如果路径可以使用
tempCost + map[tempPath[node - 1]][tempPath[i]] < minCost //如果当前花费没有超过最小花费
) {
tempCost += map[tempPath[node - 1]][tempPath[i]];//计算当前耗费
swap(&tempPath[i], &tempPath[node]);//交换节点,使node对应为当前i节点
backTrack(node + 1);//找下一个节点
swap(&tempPath[i], &tempPath[node]);//复原
tempCost -= map[tempPath[node - 1]][tempPath[i]];//复原
}
}
}
}
void Solution::SearchPath() {
backTrack(1);//从1号开始,默认0号是起点
cout << "最小花费为:" << minCost << endl;
cout << "策略为:";
for (int i = 0;i < count;i++) {
cout << path[i] + 1<< " ";
}
}
int main() {
vector<int> data;//记录数据
vector<vector<int>> map;
int num = 0;//记录节点数目
ifstream ifs("data.csv", ios_base::binary);
if (!ifs) {
return -1;
}
while (!ifs.eof()) {
int dig;
ifs >> dig;
if (ifs.fail()) {
ifs.clear();
ifs.ignore(1);
continue;
}
num++;
data.push_back(dig);
}
ifs.close();
ifs.clear();
num = sqrt(num);
for (int i = 0;i < num;i++) {
vector<int> temp(num, 0);
for (int j = 0;j < num;j++) {
temp[j] = data[i * num + j];
}
map.push_back(temp);
}
data.clear();
Solution solve(map,num);
solve.SearchPath();
}