您的位置:首页 > 其它

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

2011-05-22 19:50 253 查看
题目描述我就不说了,但是给几个测试用例

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
]+graph[x
][1]<bestc||bestc==0) && graph[x[n-1]][x
]!=-1 && graph[x
][1]!=-1 )
{
bestc=c+graph[x[n-1]][x
]+graph[x
][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]);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: