旅行员售货问题

----- 经典回溯问题

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

              

              以上图为例:售货员要从1开始经过2,3,4又返回1。

 给我的感觉就是一个排列问题。在进行计算排列的同时要判断是否该排列有必要进行下去,因为可能在中途就可以判断这样肯定得不到我们想要的结果,此时采用回溯。
 
代码实现:
 1 /*   
 2  * 售货员问题----回溯处理 
 3  */ 
 4 #include<iostream>  
 5 using namespace std;  
 6    
 7 #define MAX  1024  
 8    
 9 int N=4;                //可以自己输入,这里我就指定了,并且在init()中设定了所有点的Cost[][];  
10 int Cost[MAX][MAX];          //记录任意两点的运费或代价  
11 int bestCost=MAX;           //记录目前最少运费或代价  
12 int currentCost;            //当前运费或代价  
13 int current[MAX];           //当前路径  
14 int best[MAX];              //记录最佳路径  
15    
16 void swap(int& a,int& b)  
17 {  
18     int temp=a;  
19     a=b;  
20     b=temp;  
21 }  
22    
23 void backtrack(int t)        //其实就是一个排列问题。。。  
24 {  
25     int j;  
26     if(t==N)              //到了最后一层。。  
27     {  
28         if(Cost[current[t-1]][current[t]]+Cost[current[t]][1]+currentCost<bestCost)  
29         {  
30             bestCost=Cost[current[t-1]][current[t]]+Cost[current[t]][1]+currentCost;  
31             for(j=1;j<=N;j++)  
32             {  
33                 best[j]=current[j];  
34             }  
35         }  
36     }  
37        
38     for(j=t;j<=N;j++)        //排列。。。  
39     {  
40         swap(current[t],current[j]);  
41         if(Cost[current[t-1]][current[t]]+currentCost<bestCost)    //其实currentCost就是包括了1-->(t-1)的代价或运费  
42         {  
43             currentCost+=Cost[current[t-1]][current[t]];  
44             backtrack(t+1);                          //递归回溯  
45             currentCost-=Cost[current[t-1]][current[t]];  
46         }  
47         swap(current[t],current[j]);  
48     }  
49 }  
50    
51 void init()  
52 {  
53      Cost[1][1]=0;  
54      Cost[1][2]=30;  
55      Cost[1][3]=6;  
56      Cost[1][4]=4;  
57    
58      Cost[2][1]=30;  
59      Cost[2][2]=0;  
60      Cost[2][3]=5;  
61      Cost[2][4]=10;  
62    
63      Cost[3][1]=6;  
64      Cost[3][2]=5;  
65      Cost[3][3]=0;  
66      Cost[3][4]=20;  
67    
68      Cost[4][1]=4;  
69      Cost[4][2]=10;  
70      Cost[4][3]=20;  
71      Cost[4][4]=0;  
72 }  
73 void main()  
74 {  
75      init();  
76    
77      int i;  
78      for(i=1;i<=N;i++)  
79      {  
80          current[i]=i;  
81      }  
82    
83      backtrack(2);                    //树的第一层已经找到了,所以从第二层开始  
84    
85      cout<<"最少的运费为:"<<bestCost<<endl;  
86      cout<<"最佳路径为: ";  
87      for(i=1;i<=N;i++)  
88      {  
89          cout<<best[i]<<"->";  
90      }  
91      cout<<best[1]<<endl;  
92 }

        

OK哒!O(∩_∩)O哈哈~
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值