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 虽然偶尔会迷路,但是因为有了你的帮助 **和**从此还是过上了幸福的生活。 ――全剧终――
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112
此题我的Dijkstra算法代码老是RE,找不到错误。。。
#include <iostream> #include <cstdio> #include <map> #include <queue> using namespace std; const int INF=0x3f3f3f3f; int a[155][155]; int dis[155]; bool vis[155]; int n,m; void spfa() { for(int i=1; i<=n; i++) { dis[i]=INF; vis[i]=false; } dis[1]=0; vis[1]=true; queue<int>q; q.push(1); while(!q.empty()) { int p=q.front(); q.pop(); vis[p]=false; for(int i=1; i<=n; i++) { if(dis[i]>dis[p]+a[p][i]) { dis[i]=dis[p]+a[p][i]; if(!vis[i]) { vis[i]=true; q.push(i); } } } } } int main() { char s[35],e[35]; char ss[35],ee[35]; int d; map<string,int>mapp; while(scanf("%d",&m)!=EOF,m!=-1) { for(int i=0; i<155; i++) { for(int j=0; j<155; j++) if(i==j) a[i][j]=0; else a[i][j]=INF; } mapp.clear(); cin>>ss>>ee; n=0; mapp[ss]=++n; if(mapp[ee]==0) mapp[ee]=++n; while(m--) { scanf("%s%s%d",&s,&e,&d); if(mapp[s]==0) mapp[s]=++n; if(mapp[e]==0) mapp[e]=++n; if(a[mapp[s]][mapp[e]]>d) a[mapp[s]][mapp[e]]=a[mapp[e]][mapp[s]]=d; } spfa(); if(dis[mapp[ee]]>=INF) cout<<"-1"<<endl; else cout<<dis[mapp[ee]]<<endl; } return 0; }
HDU 2112 HDU Today【最短路+map容器,spfa算法+Dijkstra算法】
原文:http://blog.csdn.net/hurmishine/article/details/52059242