1. TSP问题
有若干个城市,任何两个城市之间的距离都是确定的,现要求一旅行商从某城市出发必须经过每一个城市且只在一个城市逗留一次,最后回到出发的城市,问如何事先确定一条最短的线路已保证其旅行的费用最少?
#include <stdio.h>
const int MAX = 999999999;
int map[20000][20000];
int visited[20000];
int city,road,visitedCity=0;
int miniRoad=MAX,nowRoad=0;
int shorterRoad[20000][2];
double lowLimit(int node)
{
int i;
double res = (shorterRoad[node][0]+shorterRoad[1][0])*2;
for(i=0;i<=city;i++)
{
if(visited[i]==0)
{
res += shorterRoad[i][0]+shorterRoad[i][1];
}
}
return res/2;
}
void TSP(int start,int nowRoad)
{
int tmp = nowRoad;
visited[start] = 1;
visitedCity++;
if(miniRoad < nowRoad + lowLimit(start)) // pruning
{
return ;
}
if(visitedCity==city) // all citise has visited, return origin
{
if(map[start][1] != 0 && miniRoad > nowRoad + map[start][1])
miniRoad = nowRoad + map[start][1];
return;
}
int i;
for(i=1;i<=city;i++)
{
if(visited[i]==0 && map[start][i]!=0) //not visited
{
nowRoad = tmp + map[start][i];
if(nowRoad > miniRoad) // pruning
continue;
TSP(i,nowRoad);
visited[i] = 0;
visitedCity--;
}
}
}
void shorterRoadForEachCity() //shorterRoad[i][0..1] save shorterRoad for ever city
{
int i,j,tmp1=MAX,tmp2=0;
for(i=1;i<=city;i++)
{
for(j=1;j<=city;j++)
{
if(map[i][j]!=0&&tmp1>map[i][j])
{
tmp2 = tmp1;
tmp1 = map[i][j];
}
}
shorterRoad[i][0] = tmp1;
shorterRoad[i][1] = tmp2;
}
}
int main()
{
scanf("%d%d",&city,&road);
int a,b,length;
while(road--)
{
scanf("%d%d%d",&a,&b,&length);
map[a][b]=length;
map[b][a]=length;
}
TSP(1,0);
printf("%d\n",miniRoad);
return 0;
}