您的位置:首页 > 其它

TSP:旅行者问题(动态规划+递归)

2011-10-08 21:02 176 查看
// TSP.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
typedef struct _node_st{
bool inPath ;
int nextIndex;
_node_st():inPath(false),nextIndex(-1){

}
}Node,*NodePtr;
#define MAX 6
int dis[MAX][MAX]={
0, 10, 20, 30, 40, 50,
12, 0 ,18, 30, 25, 21,
23, 19, 0, 5,  10, 15,
34, 32, 4, 0,  8,  16,
45, 27, 11,10, 0,  18,
56, 22, 16,20, 12,  0
};
Node p[MAX];
void printPath();
//表示从begin开始,经过所有点后到达end的最小距离
int tsp(int beginIndex,int endIndex){

int result = 0xFFFFFFF;
bool isLast = true;
for(int i=0;i<MAX;i++){

if(i!=beginIndex){

if(!p[i].inPath){
isLast = false;

p[i].inPath = true;

int value = tsp(i,endIndex);

if(dis[beginIndex][i]+value<result){

p[beginIndex].nextIndex = i;
result = dis[beginIndex][i]+value;

if(beginIndex==0&&endIndex==0){
printPath();
}

}

p[i].inPath = false;

}

}
}
if(isLast){

p[beginIndex].nextIndex = endIndex;
return dis[beginIndex][endIndex];
}
return result;
}
void printPath(){

int pre = 0,next;
int count = MAX;
while(count--){
next = p[pre].nextIndex;
printf("%d->%d ",pre,next);
pre = next;
}
printf("\n");
}
int main(int argc, char* argv[])
{
//freopen("i://out.txt","w",stdout);
p[0].inPath = true;
printf("%d\n",tsp(0,0));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: