旅行售货员问题(回溯法)

题目描述我就不说了,但是给几个测试用例

 

input
4
-1 30 6 4
30 -1 5 10
6 5 -1 20
4 10 20 -1
output
25

 

input
7
-1 -1 -1 5 10 -1 -1
-1 -1 -1 -1 -1 3 -1
-1 -1 -1 -1 -1 -1 2
-1 8 -1 -1 -1 -1 -1
-1 -1 3 -1 -1 -1 -1
-1 -1 -1 -1 1 -1 -1
9 -1 -1 -1 -1 -1 -1
output
31

//旅行售货员问题 #include<iostream> #define MAXSIZE 100 using namespace std; int n; int graph[MAXSIZE][MAXSIZE]; int c=0; int bestc=0; int x[MAXSIZE]; int bestx[MAXSIZE]; void backtrack(int k); void swap(int &a,int &b); int main(void) { cin>>n; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { cin>>graph[i][j]; } } for(int i=1;i<=n;i++) { x[i]=i; bestx[i]=i; } backtrack(2); cout<<bestc<<endl; for(int i=1;i<=n;i++) { cout<<bestx[i]<<‘ ‘; } cout<<1<<endl; return 0; } void swap(int &a,int &b) { int temp=a; a=b; b=temp; } void backtrack(int k) { if(k==n) { if( (c+graph[x[n-1]][x[n]]+graph[x[n]][1]<bestc||bestc==0) && graph[x[n-1]][x[n]]!=-1 && graph[x[n]][1]!=-1 ) { bestc=c+graph[x[n-1]][x[n]]+graph[x[n]][1]; for(int i=1;i<=n;i++) { bestx[i]=x[i]; } } return ; } else { for(int i=k;i<=n;i++) { if( graph[x[k-1]][x[i]]!=-1 && (c+graph[x[k-1]][x[i]]<bestc || bestc==0)) { swap(x[i],x[k]); c+=graph[x[k-1]][x[k]]; backtrack(k+1); c-=graph[x[k-1]][x[k]]; swap(x[i],x[k]); } } } }

    原文作者:回溯法
    原文地址: https://blog.csdn.net/fcwr_zhuxin_fcwr/article/details/6438210
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞