布线问题----回溯法

在这里插入图片描述

/*
	布线问题:

	回溯算法

	观察题目要求,需要在所有不同的排序中找出成本最低的的一种排线方式,成本计算公式: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;
}
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

call me Patrick

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值