题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112
易错点:
1)当起点等于终点时,hash会出错
2)无向图
3)两个点之间不只一条路径(取最短就好)
4)没有通路的情况(输出-1)
利用map哈希字符串,本题时限要求不高,Dijkstra就可以了
1 #include<cmath>
2 #include<cstdio>
3 #include<cstring>
4 #include<iostream>
5 #include<algorithm>
6 #include<string>
7 #include<map>
8 using namespace std;
9
10 const int inf=0x3f3f3f3f;
11 char s1[50],s2[50];
12 int d[1005],e[1005][1005],used[1005];
13
14 void dij(int s,int n)
15 { int v,u,max=0;
16 memset(used,0,sizeof(used));
17 for(u=1;u<=n;u++)
18 d[u]=inf;
19
20 d[s]=0;
21
22
23 while(1)
24 { v=-1;
25 for(u=1;u<=n;u++)
26 { if(!used[u]&&(v==-1||d[u]<d[v]))
27 v=u;
28
29 }
30 if(v==-1) break;
31 used[v]=1;
32
33 for(u=1;u<=n;u++)
34 if(d[u]>d[v]+e[v][u])
35 d[u]=d[v]+e[v][u];
36 }
37 }
38
39 int main()
40 {
41 int n;
42 while(~scanf("%d",&n))
43 { if(n==-1) break;
44 map <string,int> mp;
45
46 for(int i=0;i<=200;i++)
47 for(int j=0;j<=200;j++)
48 e[i][j]=inf;
49
50 scanf("%s%s",s1,s2);
51 mp[s1]=1;mp[s2]=2;
52 if(strcmp(s1,s2)==0)
53 {
54 e[1][2]=0;
55 }
56 int num=2;
57 for(int i=0;i<n;i++)
58 { int w;
59 scanf("%s%s%d",s1,s2,&w);
60 if(mp[s1]==0) mp[s1]=++num;
61 if(mp[s2]==0) mp[s2]=++num;
62 e[mp[s1]][mp[s2]]=min(e[mp[s1]][mp[s2]],w);
63 e[mp[s2]][mp[s1]]=min(e[mp[s2]][mp[s1]],w);
64 }
65 dij(1,num);
66 if(d[2]<2000000)
67 printf("%d\n",d[2]);
68 else printf("-1\n");
69 }
70 }