用动态规划解决TSP问题

状态压缩DP

include"stdio.h"
#include"stdlib.h"
#define MIN(a,b) (a<b)?a:b
int main(int argc,char* argv[]){
   freopen(argv[1],"r",stdin);
   const int SIZE=10; 
   double array[SIZE][SIZE];
   double dp[SIZE][1<<SIZE];
   int n;
   scanf("%d",&n);
   for(int i=0;i<n;++i)
      for(int j=0;j<n;++j)
          scanf("%lf",&array[i][j]);
   for(int j=1;j<n;++j)
      dp[j][0]=array[j][0];
   int upperBound=1<<(n-1);
   for(int i=1;i<upperBound;++i){
      for(int j=0;j<n;++j){
         if(j!=0 &&(i&(1<<(j-1)))) continue;//illegal condition
         for(int k=1;k<n;++k){
            if(j==k) continue;
            if( i&(1<<(k-1)) ){
               if(dp[j][i]==0)
                  dp[j][i]=array[j][k]+dp[k][i-(1<<(k-1))];
               else
                  dp[j][i]=MIN(dp[j][i],array[j][k]+dp[k][i-(1<<(k-1))]);
            }
         }
      }
   }
   printf("%lf\n",dp[0][upperBound-1]);
   return 0;
}                                                                                        
    原文作者:动态规划
    原文地址: https://blog.csdn.net/shiyang6017/article/details/51016526
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞