zoukankan      html  css  js  c++  java
  • TSP:旅行者问题(动态规划+递归)

    // 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;
    }
    
    

    躲猫猫社团团长 http://t.sina.com.cn/coolria

  • 相关阅读:
    欧拉回路
    2018 年 ACM-ICPC 焦作站现场赛感受
    3.1 基础-抛小球
    2.2 进阶-禁忌雷炎
    初学Java-循环输入直到文件结束
    1.1 基础-取近似值
    1.2 进阶-对称的二叉树
    LEETCODE
    算法
    算法
  • 原文地址:https://www.cnblogs.com/yangyh/p/2202995.html
Copyright © 2011-2022 走看看