輸入樣例 |
輸出樣例 |
4 6 1 2 20 1 4 4 1 3 6 2 3 5 2 4 10 3 4 15 0 |
1 3 2 4 25
|
完整程序:
#include<bits/stdc++.h>
using namespace std;
//旅行商問題回溯算法
//(1) 旅行商問題回溯算法的數據結構
#define NUM 100
int n; //圖G的頂點數量
int m; //圖G的邊數
int a[NUM][NUM]; //圖G的鄰接矩陣
int x[NUM]; //當前解
int bestx[NUM]; //當前最優解向量
int cc; //當前費用
int bestc; //當前最優值
int NoEdge = -1; //無邊標記
//(2) 旅行商問題回溯算法的實現
//形參t是回溯的深度,從2開始
void Backtrack(int t)
{
//到達葉子結點的父結點
if(t==n)
{
if(a[x[n-1]][x[n]]!=NoEdge&&a[x[n]][1]!=NoEdge &&
(cc+a[x[n-1]][x[n]]+a[x[n]][1]<bestc||bestc==NoEdge))
{
for(int i=1;i<=n;i++)
bestx[i]=x[i];
bestc=cc+a[x[n-1]][x[n]]+a[x[n]][1];
}
return;
}
else
{
for(int i=t;i<=n;i++)
{
if(a[x[t-1]][x[i]]!=NoEdge&&
(cc+a[x[t-1]][x[i]]<bestc||bestc==NoEdge))
{
swap(x[t],x[i]);
cc+=a[x[t-1]][x[t]];
Backtrack(t+1);
cc-=a[x[t-1]][x[t]];
swap(x[t],x[i]);
}
}
}
}
int main(){
int a1,b1,c1;
cout<<"請輸入頂點數和邊數"<<endl;
while(cin>>n){
if(n>0){
cin>>m;
//在構造鄰接矩陣a時,其初始值應爲NoEdge:
int i,j;
for (i=0; i<NUM; i++)
for (j=1; j<NUM; j++)
a[i][j] = NoEdge;
//最優值和向量x的初始化數值如下:
bestc = NoEdge;
for(i=1; i<=n; i++)
x[i] = i;
cout<<"請輸入有邊的點及其之間的權重:"<<endl;
for(int i=0;i<m;i++){
cin>>a1>>b1>>c1;
a[a1][b1]=c1;
a[b1][a1]=c1;
}
Backtrack(2);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"當前最優解向量爲:"<<endl;
for(int i=1;i<=n;i++){
cout<<bestx[i]<<" ";
}
cout<<endl;
cout<<"當前最優值爲:"<<endl;
cout<<bestc<<endl;
cout<<"請輸入頂點數和邊數"<<endl;
}else{
break;
}
}}