http://acm.hdu.edu.cn/showproblem.php?pid=2112
注意:起终点相同,map保存出现的地点
#include<iostream>
#include<cstdio>
#include<map>
#include<string>
using namespace std;
const int NM=155;
const int MAX=0x3fffffff;
int a[NM][NM];
map<string,int>m1;
int main()
{
int m,i,j,nn,time,k1,k2,k,flag;
string str1,str2;
while(cin>>m&&m>-1)
{
m1.clear();
map<string,int>m1;
for(i=1;i<NM;i++)
{
a[i][i]=0;
for(j=1;j<NM;j++)
a[i][j]=MAX;
}
cin>>str1>>str2;
i=1;flag=0;
m1[str1]=i++;
if(str1!=str2) m1[str2]=i++;
else flag=1;
for(j=0;j<m;j++)
{
cin>>str1>>str2>>time;
if(m1[str1]>0) //不能用<0
k1=m1[str1];
else
{
k1=i;
m1[str1]=i++;
}
if(m1[str2]>0)
k2=m1[str2];
else
{
k2=i;
m1[str2]=i++;
}
if(time<a[k1][k2]) //无向图
a[k1][k2]=a[k2][k1]=time;
}
if(flag)
{
cout<<0<<endl;
continue;
}
nn=i;
for(k=1;k<=nn;k++)
for(i=1;i<=nn;i++)
if(a[i][k]!=MAX)
{
for(j=1;j<=nn;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
a[i][j]=a[i][k]+a[k][j];
}
}
if(a[1][2]==MAX) cout<<"-1"<<endl;
else cout<<a[1][2]<<endl;
}
return 0;
}