6 xiasha westlake xiasha station 60 xiasha ShoppingCenterofHangZhou 30 station westlake 20 ShoppingCenterofHangZhou supermarket 10 xiasha supermarket 50 supermarket westlake 10 -1
50 Hint: The best route is: xiasha->ShoppingCenterofHangZhou->supermarket->westlake 这道题目就是一道裸的最短路问题,但是这里有个棘手的地方就是,地名都是用字符串表示,而不像我们平时做的题目用数字来表示。所以我们需要用到map函数来巧妙地处理这个问题。 我用的是dijkstra算法+邻接表做的。代码如下://dijkstra算法 #include<map> #include<queue> #include<math.h> #include<vector> #include<string> #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int max_d=150+5; const int max_n=99999999; const int max_G=150+5; struct Edge{ int to,dis; Edge(int to,int dis){ this -> to = to; this -> dis = dis; } }; map<string,int>m; vector<Edge>G[max_G]; typedef pair<int,int>P; int n,t,pot; int d[max_d]; char ss[100],sss[100]; char s1[100],s2[100]; void dijkstra() { priority_queue<P,vector<P>,greater<P> >q; fill(d+1,d+pot+1,max_n); while(q.size()) q.pop(); d[1]=0; q.push(P(0,1)); while(q.size()){ P p=q.top(); q.pop(); int v=p.second; if(d[v]<p.first) continue; for(int i=0;i<G[v].size();i++){ Edge& e=G[v][i]; if(d[e.to]>d[v]+e.dis){ d[e.to]=d[v]+e.dis; q.push(P(d[e.to],e.to)); } } }if(d[2]==max_n) printf("-1\n"); else printf("%d\n",d[2]); } int main() { while(scanf("%d",&n)!=EOF){ if(n==-1) break; m.clear(); //初始化map for(int i=0;i<155;i++) G[i].clear(); //初始化邻接表 scanf("%s%s",ss,sss); m[ss]=1; m[sss]=2; pot=2; for(int i=0;i<n;i++) { scanf("%s%s%d",s1,s2,&t); if(!m.count(s1)){ pot++; m[s1]=pot; } if(!m.count(s2)){ pot++; m[s2]=pot; } G[m[s1]].push_back(Edge(m[s2],t)); G[m[s2]].push_back(Edge(m[s1],t)); } if(strcmp(ss,sss)==0) printf("0\n"); //起点和终点相同 else dijkstra(); }return 0; }
HDU-2112-最短路(map),布布扣,bubuko.com
原文地址:http://blog.csdn.net/jhgkjhg_ugtdk77/article/details/38134441