链接: http://acm.hdu.edu.cn/showproblem.php?pid=2112
最短路,dijkstra
输入为字符串,用C++ STL map处理成数字后存入图
#include <cstdio>
#include <iostream>
#include <cstring>
#include <map>
#define INF 0x3f3f3f3f
using namespace std;
int mp[151][151];
bool used[151];
void Dijk(int n)
{
int T=n;
memset(used,0,sizeof(used));
used[1]=1;
while(T--)
{
int mini=INF,k;
for(int i=1;i<=n;i++)
if(!used[i] && mini>mp[1][i])
mini=mp[1][k=i];
if(mini==INF) break;
used[k]=1;
for(int i=1; i<=n; i++)
if(!used[i] && mp[1][i]>mp[1][k]+mp[k][i])
mp[1][i]=mp[1][k]+mp[k][i];
}
}
int main()
{
int n,cnt,dis;
char str1[32],str2[32];
bool flag;
map <string, int> stop;
while(~scanf("%d",&n) && n+1)
{
flag=0;
cnt=3;
memset(mp,INF,sizeof(mp));
stop.clear();
scanf("%s %s",str1,str2);
if(!strcmp(str1,str2)) flag=1;
stop[str1]=1;
stop[str2]=2;
for(int i=1; i<=n; i++)
{
scanf("%s %s %d",str1,str2,&dis);
if(!stop[str1]) stop[str1]=cnt++;
if(!stop[str2]) stop[str2] = cnt++;
if(dis<mp[stop[str1]][stop[str2]])
mp[stop[str1]][stop[str2]]=mp[stop[str2]][stop[str1]]=dis;
}
if(flag)
{
printf("0\n");
continue;
}
Dijk(cnt-1);
printf(mp[1][2]==INF ? "-1\n" : "%d\n",mp[1][2]);
}
return 0;
}