Samball is going to travel in the coming vacation. Now it's time to make a plan. After choosing the destination city, the next step is to determine the travel route. As this poor guy has just experienced a tragic lost of money, he really has limited amount of money to spend. He wants to find the most costless route. Samball has just learned that the travel company will carry out a discount strategy during the vacation: the most expensive flight connecting two cities along the route will be free. This is really a big news.
Now given the source and destination cities, and the costs of all the flights, you are to calculate the minimum cost. It is assumed that the flights Samball selects will not have any cycles and the destination is reachable from the source.
Input
The input contains several test cases, each begins with a line containing names of the source city and the destination city. The next line contains an integer m (<=100), the number of flights, and then m lines follow, each contains names of the source city
and the destination city of the flight and the corresponding cost. City names are composed of not more than 10 uppercase letters. Costs are integers between 0 to 10000 inclusively.
Process to the end of file.
Output
For each test case, output the minimum cost in a single line.
Sample Input
HANGZHOU BEIJING
2
HANGZHOU SHANGHAI 100
SHANGHAI BEIJING 200
Sample Output
100
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int inf=(1<<28);
map<string,int> q;
int n;
int a[110][110];//a[i][j]表示从i到j的最少花费(减去p[i][j]后的)
int p[110][110];//p[i][j]表示i->j最少花费路上的最大花费
char st[110],ed[110];
char str1[100],str2[100];
int main()
{
while(scanf("%s%s",st,ed)==2)
{
int e;scanf("%d",&e);
n=0;
q.clear();
memset(a,-1,sizeof(a));
while(e--)
{
int w;
scanf("%s%s%d",str1,str2,&w);
if(q[str1]==0) q[str1]=++n;
if(q[str2]==0) q[str2]=++n;
a[q[str1]][q[str2]]=w;
}
for(int i=1;i<=n;i++)
{
a[i][i]=0;
for(int j=1;j<=n;j++)
{
if(a[i][j]!=-1) p[i][j]=a[i][j],a[i][j]=0;
}
}
for(int k=1;k<=n;k++)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][k]!=-1&&a[k][j]!=-1)
{
int tmp=a[i][k]+a[k][j]+min(p[i][k],p[k][j]);
if(a[i][j]==-1)
{
a[i][j]=tmp;
p[i][j]=max(p[i][k],p[k][j]);
}
else if(a[i][j]>tmp)
{
a[i][j]=tmp;
p[i][j]=max(p[i][k],p[k][j]);
}
}
}
}
}
printf("%d\n",a[q[st]][q[ed]]);
}
return 0;
}
本文介绍了一种寻找最经济旅行路线的算法实现,通过处理输入的多个案例,计算在特定优惠策略下从源城市到目标城市的最低旅行成本。该算法考虑了免费最昂贵航班的因素,确保旅行成本最小。
294

被折叠的 条评论
为什么被折叠?



