/*
布线问题:
回溯算法
观察题目要求,需要在所有不同的排序中找出成本最低的的一种排线方式,成本计算公式:dist(r,s) * (求和)conn(i,j)
由于回溯其实也是一种暴力算法,不过多加了一端判断条件导致可以遍历较少的情况数
回溯问题无非就两种:1. 子集问题 2. 全排列问题
显然这个是一种全排列问题,直接可以利用Perm算法来解决
*/
#include <iostream>
#include <fstream>
using namespace std;
const int Max = 20;
int n; // 原件的个数
int best[Max]; // 用来存放最低成本的排序方式
int nect_cost[Max+1][Max+1]; // 用来放置原件之间的连线数
int curr_arr[Max]; // 当前排线
int min_Cost = 1000000000; // 最小成本
int curr_Cost = 0; // 当前成本
// 更新排线函数
void upgrade() {
for (int i = 0; i < Max; i++)
best[i] = curr_arr[i];
}
// 交换函数
void Swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int caculate_Cost(int depth) {
int cost = 0;
for (int i = 1; i < depth; i++) {
for (int j = i + 1; j <= depth; j++) {
cost += (j - i) * nect_cost[curr_arr[i]][curr_arr[j]];
}
}
return cost;
}
// 依照回溯函数模板编写回溯函数,其中形式参数代表着递归的层数
void traceBack(int depth) {
/*
依照函数模板,第一步是写出递归的终止条件
显然当递归的层数 与 所给的原件的个数相同的时候需要终止并更新
*/
if (depth > n) {
min_Cost = curr_Cost;
upgrade();
return;
}
else {
// 回溯法最重要的就是设置剪枝策略,这里的剪枝策略时如果当前的成本大于最低成本可以直接继续向下递归搜索
// 这里就是正常的模板,利用Perm函数进行遍历
for (int i = depth; i <= n; i++) {
Swap(curr_arr[depth], curr_arr[i]);
// 计算交换后的当前成本
curr_Cost = caculate_Cost(depth);
// 递归
if (curr_Cost <= min_Cost)
traceBack(depth + 1);
// 回溯
Swap(curr_arr[depth], curr_arr[i]);
curr_Cost = caculate_Cost(depth);
}
}
}
int main() {
// 输出初始化
memset(curr_arr, 0, sizeof(curr_arr));
memset(nect_cost, 0, sizeof(nect_cost));
memset(best, 0, sizeof(best));
ifstream datain("input_data2.txt");
cout << "\n输入人原件的个数:"; datain >> n; cout << n;
cout << endl << endl;
for (int i = 1; i <= n; i++)
curr_arr[i] = i;
for (int i = 1; i < n; i++) {
cout << "第" << i << "个原件与" << i + 1 << "..." << n << "等原件之间的连线数分别为:";
for (int j = i + 1; j <= n; j++) {
datain >> nect_cost[i][j];
nect_cost[j][i] = nect_cost[i][j];
cout << nect_cost[i][j] << " ";
}
cout << endl << endl;
}
// 回溯递归算法
traceBack(1);
ofstream dataout("output_data2.txt",ios::trunc);
dataout << min_Cost << endl;
cout << "最小布线成本:" << min_Cost << endl << endl;
cout << "最小布线方案:";
for (int i = 1; i <= n; i++) {
dataout << best[i] << " ";
cout << best[i] << " ";
}
cout << endl;
return 0;
}
布线问题----回溯法
最新推荐文章于 2023-03-23 21:17:30 发布