当前位置:   article > 正文

HNU_算法_实验4(2021级)-经典案例2-分支限界法求解TSP问题_基于分支限界法求解tsp等问题

基于分支限界法求解tsp等问题

  一、实验名称

分支限界法求解TSP问题;

        问题描述:某售货员要到若干城市去推销商品,已知各城市之间的路程,他要选定一条从驻地出发,经过每个城市一遍,最后回到住地的路线,使总的路程最短。

二、实验目的

        通过上机实验,要求掌握分支限界法求解TSP问题的问题描述、算法设计思想、程序设计。

三、实验原理

        利用分支限界法求解TSP问题,并计算出程序运行所需要的时间。

四、实验步骤

       算法描述:

        解旅行售货员问题的优先队列式分支限界法用优先队列存储活结点表。

活结点m在优先队列中的优先级定义为:活结点m对应的子树费用下界lcost。

        lcost=cc+rcost,其中,cc为当前结点费用,rcost为当前顶点最小出边费用加上剩余所有顶点的最小出边费用和。

        优先队列中优先级最大的活结点成为下一个扩展结点

        排列树中叶结点所相应的载重量与其优先级(下界值)相同,即:叶结点所相应的回路的费用(bestc)等于子树费用下界lcost的值。

       

        

五、关键代码

1.排列树的节点定义

  1. struct node
  2. {
  3. int cl;//当前走过的路径长度
  4. int id;//处理的第几个城市
  5. int x[1000];//记录当前路径,下标从1开始
  6. node() {}
  7. node(int cl_,int id_)
  8. {
  9. cl=cl_;
  10. id=id_;
  11. memset(x,0,sizeof(x));
  12. }
  13. };

2.用于构建最小堆(优先队列)

  1. struct cl_cmp {
  2. //当前路径长度短的优先级高
  3. bool operator()(node n1, node n2)
  4. {
  5. return n1.cl > n2.cl;
  6. }
  7. };
  8. void bfs(int n,int &bestl,vector<int> &bestx,vector<vector<int> > &m)
  9. {
  10. //选用最小堆
  11. priority_queue<node,vector<node>,cl_cmp> q;
  12. //创建一个节点,从该节点开始,因为1是固定位,其实是从1开始探索
  13. node temp(0,2);
  14. //初始化解向量
  15. for(int i=1; i<=n; ++i)
  16. temp.x[i]=i;
  17. q.push(temp);
  18. node cur;//当前节点,也就是活节点
  19. int t;
  20. while(!q.empty())
  21. {
  22. cur=q.top();
  23. q.pop();
  24. t=cur.id;
  25. if(t==n)
  26. {
  27. //满足约束条件,有路径
  28. //检测图G是否存在一条从顶点x[n-1]到顶点x[n]的边和一条从顶点x[n]到顶点1的边
  29. if(m[cur.x[t-1]][cur.x[t]]!=INF&&m[cur.x[t]][1]!=INF)
  30. {
  31. if(cur.cl+m[cur.x[t-1]][cur.x[t]]+m[cur.x[t]][1]<bestl)
  32. {
  33. //更新最优解和最优路径
  34. bestl=cur.cl+m[cur.x[t-1]][cur.x[t]]+m[cur.x[t]][1];
  35. for(int i=1; i<=n; ++i)
  36. bestx[i]=cur.x[i];
  37. }
  38. }continue;
  39. }
  40. //大于等于最优路径,没必要继续探索了,从下一个节点开始
  41. if(cur.cl>=bestl)
  42. continue;
  43. //从当前节点开始探索t-1 -> t,t+1,t+2...
  44. for(int j=t; j<=n; ++j)
  45. {
  46. //满足约束条件和限界条件
  47. if(m[cur.x[t-1]][cur.x[j]]!=INF&&cur.cl+m[cur.x[t-1]][cur.x[j]]<bestl)
  48. {
  49. temp=node(cur.cl+m[cur.x[t-1]][cur.x[j]],t+1);
  50. //如果找到了一个下级节点,那么该节点到现在为止和同级的节点路径相同,除了当前这一级的不同
  51. for(int k=1; k<=n; ++k)
  52. temp.x[k]=cur.x[k];
  53. swap(temp.x[t],temp.x[j]);
  54. q.push(temp);
  55. }
  56. }
  57. }
  58. }

3.不同规模案例生成

        顶点个数为n,所以可能有n*n个权重。

        但是可能有一些节点之间无可达边,所以下面还设置了一个参数probability,作为矩阵中不可达边的概率,来设置权重矩阵的“稀疏”程度。

        而且由于INF的存在,所以权重并不能无限制的大。而且我们也没有需求将这类值设的很大(不影响复杂度),不妨限制在0-100之间的整数。

  1. // 设置概率值,矩阵中不可达边的概率
  2. double probability = 0.1;
  3. // c数组 不妨设置权重范围为(a,b]
  4. int a=0,b=100;
  5. for(int i=1;i<=n;i++){
  6. for(int j=1;j<=n;j++) {
  7. // 生成一个介于0到1之间的随机小数
  8. double randomValue = static_cast<double>(std::rand()) / RAND_MAX;
  9. if (randomValue < probability) {
  10. // 有probability的概率输出INF
  11. out<< INF <<' ';
  12. }
  13. else {
  14. // 有(1 - probability)的概率输出(a,b]间的整数
  15. out<< (rand() % (b-a))+ a + 1<<' ';
  16. }
  17. }
  18. out<<'\n';
  19. }

六、测试结果

时间复杂性:O(n!)

        分支限界法解决TSP,搜索树的节点数取决于图中城市的数量。在每一层,都需要考虑从当前城市到所有其他未访问的城市的分支,因此搜索树的规模呈指数级增长。

        具体来说,TSP问题的时间复杂度可以表示为 O(n!),其中 n 是城市的数量。这是因为在每个决策点,需要考虑 n 种可能的下一步选择,而搜索树的深度为 n。

        然而,通过一些优化策略,如减枝和启发式方法,来尽量减少搜索树的规模,以提高算法的效率。在实践中,TSP问题的解决往往依赖于问题的具体实例和算法的实现方式。

n从10-500,每次递增10的测试结果:

自定义输入n的数值的测试结果:

七、实验心得

        通过这次实验,我更为掌握了分支限界法求解TSP问题,并且自己生成案例并测试运行时间的过程中,熟悉了随机化算法和运行时间的计算。

​         实验可改进的地方:随机化过程的加入可能使得不同规模的测试数据与理论值有偏差,可以通过每个输入规模多次测试来减小误差。

八、完整代码

  1. #include <iostream>
  2. #include <cstring>
  3. #include <queue>
  4. #include <fstream>
  5. #include <vector>
  6. #include <windows.h>
  7. #include <time.h>
  8. #define INF 1e7
  9. using namespace std;
  10. //排列树的节点定义
  11. struct node
  12. {
  13. int cl;//当前走过的路径长度
  14. int id;//处理的第几个城市
  15. int x[501];//记录当前路径,下标从1开始
  16. node() {}
  17. node(int cl_,int id_)
  18. {
  19. cl=cl_;
  20. id=id_;
  21. memset(x,0,sizeof(x));
  22. }
  23. };
  24. //用于构建最小堆
  25. struct cl_cmp {
  26. //当前路径长度短的优先级高
  27. bool operator()(node n1, node n2)
  28. {
  29. return n1.cl > n2.cl;
  30. }
  31. };
  32. void bfs(int n,int &bestl,vector<int> &bestx,vector<vector<int> > &m)
  33. {
  34. //选用最小堆
  35. priority_queue<node,vector<node>,cl_cmp> q;
  36. //创建一个节点,从该节点开始,因为1是固定位,其实是从1开始探索
  37. node temp(0,2);
  38. //初始化解向量
  39. for(int i=1; i<=n; ++i)
  40. temp.x[i]=i;
  41. q.push(temp);
  42. node cur;//当前节点,也就是活节点
  43. int t;
  44. while(!q.empty())
  45. {
  46. cur=q.top();
  47. q.pop();
  48. t=cur.id;
  49. if(t==n)
  50. {
  51. //满足约束条件,有路径
  52. //检测图G是否存在一条从顶点x[n-1]到顶点x[n]的边和一条从顶点x[n]到顶点1的边
  53. if(m[cur.x[t-1]][cur.x[t]]!=INF&&m[cur.x[t]][1]!=INF)
  54. {
  55. if(cur.cl+m[cur.x[t-1]][cur.x[t]]+m[cur.x[t]][1]<bestl)
  56. {
  57. //更新最优解和最优路径
  58. bestl=cur.cl+m[cur.x[t-1]][cur.x[t]]+m[cur.x[t]][1];
  59. for(int i=1; i<=n; ++i)
  60. bestx[i]=cur.x[i];
  61. }
  62. }continue;
  63. }
  64. //大于等于最优路径,没必要继续探索了,从下一个节点开始
  65. if(cur.cl>=bestl)
  66. continue;
  67. //从当前节点开始探索t-1 -> t,t+1,t+2...
  68. for(int j=t; j<=n; ++j)
  69. {
  70. //满足约束条件和限界条件
  71. if(m[cur.x[t-1]][cur.x[j]]!=INF&&cur.cl+m[cur.x[t-1]][cur.x[j]]<bestl)
  72. {
  73. temp=node(cur.cl+m[cur.x[t-1]][cur.x[j]],t+1);
  74. //如果找到了一个下级节点,那么该节点到现在为止和同级的节点路径相同,除了当前这一级的不同
  75. for(int k=1; k<=n; ++k)
  76. temp.x[k]=cur.x[k];
  77. swap(temp.x[t],temp.x[j]);
  78. q.push(temp);
  79. }
  80. }
  81. }
  82. }
  83. int main(){
  84. ofstream out1("output.txt");
  85. int n=500;
  86. while(n-=10){
  87. // //生成规模为n的随机数
  88. // cout<<"请输入顶点个数n:"<<endl;
  89. // int n;
  90. // cin>>n;
  91. ofstream out("input1.txt");
  92. out<<n<<'\n';
  93. srand((unsigned)time(NULL));
  94. // 设置概率值,矩阵中不可达边的概率
  95. double probability = 0.1;
  96. // c数组 不妨设置权重范围为(a,b]
  97. int a=0,b=100;
  98. int i,maxi,mini;
  99. LARGE_INTEGER nFreq,nBegin,nEnd;
  100. double time;
  101. QueryPerformanceFrequency(&nFreq);
  102. QueryPerformanceCounter(&nBegin);
  103. for(int i=1;i<=n;i++){
  104. for(int j=1;j<=n;j++) {
  105. // 生成一个介于0到1之间的随机小数
  106. double randomValue = static_cast<double>(std::rand()) / RAND_MAX;
  107. if (randomValue < probability) {
  108. // 有probability的概率输出INF
  109. out<< INF <<' ';
  110. }
  111. else {
  112. // 有(1 - probability)的概率输出(a,b]间的整数
  113. out<< (rand() % (b-a))+ a + 1<<' ';
  114. }
  115. }
  116. out<<'\n';
  117. }
  118. QueryPerformanceCounter(&nEnd);
  119. time=(double)(nEnd.QuadPart-nBegin.QuadPart)/(double)nFreq.QuadPart;
  120. cout<<"生成时间:"<<time<<endl;
  121. out.close();
  122. ifstream in("input1.txt");
  123. in>>n;
  124. // cout<<"n= "<<n<<endl;
  125. vector<vector<int> > m(n+1, vector<int>(n+1));
  126. vector<int> bestx(n+1);
  127. int bestl=INF;//最优解长度
  128. for(i=1;i<=n;i++){
  129. for(int j=1;j<=n;j++){
  130. in>>m[i][j];
  131. // cout<<m[i][j]<<" ";
  132. }
  133. // cout<<endl;
  134. }
  135. QueryPerformanceFrequency(&nFreq);
  136. QueryPerformanceCounter(&nBegin);
  137. bfs(n, bestl, bestx, m);
  138. QueryPerformanceCounter(&nEnd);
  139. time=(double)(nEnd.QuadPart-nBegin.QuadPart)/(double)nFreq.QuadPart;
  140. cout<<"最优值为:"<<bestl<<endl;
  141. cout<<"最优解为:";
  142. for(int i=1; i<=n; ++i)
  143. cout<<bestx[i]<<" ";
  144. cout<<bestx[1]<<endl;
  145. cout<<"查询时间:"<<time<<endl<<endl;
  146. out1<<n<<' '<<time<<endl;
  147. in.close();
  148. }
  149. out1.close();
  150. return 0;
  151. }

九、绘图代码

  1. import matplotlib.pyplot as plt
  2. def read_file(filename):
  3. data = []
  4. with open(filename, 'r') as file:
  5. for line in file:
  6. x, y = map(float, line.split())
  7. data.append((x, y))
  8. return data
  9. # 读取文件的数据
  10. file3_data = read_file('F:\\3-CourseMaterials\\3-1\\3-算法设计与分析\实验\lab4\\1-code\\2-分支限界法求解TSP问题\\output.txt')
  11. # 分别提取 x 和 y 的值
  12. file3_x, file3_y = zip(*file3_data)
  13. print(file3_x)
  14. print(file3_y)
  15. # 绘制图形,指定不同颜色
  16. # plt.plot(file1_x, file1_y, label='Solution 1', color='red')
  17. # plt.plot(file2_x, file2_y, label='Solution 2', color='green')
  18. plt.plot(file3_x, file3_y, label='Solution 1', color='red')
  19. # 添加图例、标签等
  20. plt.legend()
  21. plt.title('Data from Three Files')
  22. plt.xlabel('X-axis')
  23. plt.ylabel('Y-axis')
  24. # 显示图形
  25. plt.show()


                      

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号