TSP问题(Traveling saleman problem)是指旅行家要旅行n个城市,要求经历各个城市且仅经历一次然后回到出发城市,并要求所走的路程最短。
算法:找到邻接最短路线。此贪心方法可以给出较好的近似解,但难以保证该近似解以何种程度近似于最优解。
代码如下:TSPLength 路径长度和,n 顶点个数,start 开始点,flag[] 0为未加入集合、1为已加入集合,edgeCount 加入集合的顶点个数,begin 起始点,end 终点。
int TSP(int arc[100][100],int n,int start){
int edgeCount = 1,TSPLength = 0;//edgeCount为加入集合的顶点个数
int min,begin,end;
int flag[n+1] = {0};//顶点均未加入集合,n为顶点个数
begin = start;flag[begin] = 1;//start为起始点
while(edgeCount < n){
min = 100;
for(int i=1;i<=n;i++){//找到未加入集合的最小临边
if(flag[i] == 0){
if((arc[begin-1][i-1] != 0) && (arc[begin-1][i-1] < min)){
end = i;min = arc[begin-1][i-1];
}
}
}
TSPLength += min;
flag[end] = 1;edgeCount++;//将顶点加入路径
cout<<begin<<"-->"<<end<<endl;//输出经过的路径
begin = end;//下一次从顶点v出发
}
cout<<begin<<"-->"<<start<<endl;//输出最后的回边
return TSPLength + arc[begin-1][start-1];//返回回路长度
}
图的构建如下:
struct Graph{
int Vex[100];//顶点
int arc[100][100];//边的权
int vexnum,arcnum;//顶点数、边数
};
void InitGraph(Graph &G){
G.vexnum = G.arcnum = 0;
}
void InsertVex(Graph &G,int v){
G.Vex[G.vexnum++] = v;
}
int LocateVex(Graph &G,int v){
for(int i=0;i<=G.vexnum;i++)
if(v == G.Vex[i]) return i;
return -1;
}
void InsertEdge(Graph &G,int v1,int v2,int e){
int v1num = LocateVex(G,v1);
int v2num = LocateVex(G,v2);
G.arc[v1num][v2num] = G.arc[v2num][v1num] = e;
G.arcnum += 2;
}
void ShowGraph(Graph &G){
cout<<"代价矩阵:"<<endl;
cout<<" ";
for(int i=0;i<G.vexnum;i++)
cout<<G.Vex[i]<<" ";
cout<<endl;
for(int i=0;i<G.vexnum;i++){
cout<<G.Vex[i]<<" ";
for(int j=0;j<G.vexnum;j++){
if(G.arc[i][j] == 0) cout<<"∞"<<" ";
else cout<<G.arc[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
测试如下:
int main(){
Graph G;
InitGraph(G);
InsertVex(G,1);
InsertVex(G,2);
InsertVex(G,3);
InsertVex(G,4);
InsertVex(G,5);
InsertEdge(G,1,2,3);
InsertEdge(G,1,3,3);
InsertEdge(G,1,4,2);
InsertEdge(G,1,5,6);
InsertEdge(G,2,3,7);
InsertEdge(G,2,4,3);
InsertEdge(G,2,5,2);
InsertEdge(G,3,5,5);
InsertEdge(G,3,4,2);
InsertEdge(G,4,5,3);
ShowGraph(G);
int length = TSP(G.arc,5,1);
cout<<"length = "<<length<<endl;
return 0;
}
输出如下:
代价矩阵:
1 2 3 4 5
1 ∞ 3 3 2 6
2 3 ∞ 7 3 2
3 3 7 ∞ 2 5
4 2 3 2 ∞ 3
5 6 2 5 3 ∞
1-->4
4-->3
3-->5
5-->2
2-->1
length = 14