题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112
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
真是醉了的题目,错了n次,有题意理解错误,数组开小错误等等,,不忍直视了
贴一个用map做的吧
【源代码】
#include <cstdio> #include <queue> #include <string> #include <cstring> #include <iostream> #include <vector> #include <map> using namespace std; const int maxn = 155; const int maxe = 155; const int INF = 0xfffffff; int n,cnt; int minDist[maxn]; bool inqueue[maxn]; int head[maxn];int edgeNum=0; struct node{ int to,len,next; node(int to=0,int len=0):to(to),len(len){} }edge[20005]; //开10010就re了 void addEdge(int a,int b,int len){ edge[edgeNum].to=b; edge[edgeNum].len=len; edge[edgeNum].next=head[a]; head[a]=edgeNum++; } void init(){ memset(head,-1,sizeof(head)); edgeNum=0; } int SPFA(){ for(int i=1;i<=cnt;i++){ minDist[i]=INF; inqueue[i]=0; } queue<int>Q; inqueue[1]=1; Q.push(1); minDist[1]=0; while(!Q.empty()){ int v1 =Q.front(); Q.pop(); inqueue[v1]=0; for(int i=head[v1];i!=-1;i=edge[i].next){ int v2=edge[i].to; int len=edge[i].len; if(minDist[v2]>minDist[v1]+len){ minDist[v2]=minDist[v1]+len; if(!inqueue[v2]){ inqueue[v2]=1; Q.push(v2); } } } } if(minDist[2]>=INF) return -1; return minDist[2]; } int main(){ map<string,int>mp; //遇到字符串根int匹配的题,果断用map!! char st[35],end[35]; char tmp1[35],tmp2[35]; int len; while(scanf("%d",&n)!=EOF){ if(n==-1) break; init(); mp.clear(); //不要忘了清空 cnt=0; scanf("%s %s",st,end); mp[st]=++cnt; if(mp[end]==0){ //开头结尾不一样时 mp[end]=++cnt; } for(int i=0;i<n;i++){ scanf("%s%s%d",tmp1,tmp2,&len); if(mp[tmp1]==0) mp[tmp1]=++cnt; if(mp[tmp2]==0) mp[tmp2]=++cnt; addEdge(mp[tmp1],mp[tmp2],len); addEdge(mp[tmp2],mp[tmp1],len); } if(mp[st]==mp[end]){ printf("0\n");continue; } int ans=SPFA(); printf("%d\n",ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/chaiwenjun000/article/details/47700617