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

  • 相关阅读:
    快速排序
    09-HQL:Group、Order
    08-表属性操作
    07-数据导出及动态分区
    06-数据加载
    05-Hive数据操作
    04-表操作2
    03-表操作1
    [原创]IPV4分组的格式
    mysql中having和where的区别
  • 原文地址:https://www.cnblogs.com/yangyh/p/2202995.html
Copyright © 2011-2022 走看看