题目链接: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; }
【Floyd-Warshall】
#include <iostream> #include <cstdio> #include <map> #include <string> using namespace std; int n,cnt; const int maxn = 155; const int INF = 0xfffffff; int Map[155][155]; void init(){ for(int i=0;i<maxn;i++){ for(int j=0;j<maxn;j++){ if(i==j) Map[i][j]=0; else{ Map[i][j]=INF; } } } } int main(){ map<string,int>mp; string st,end,tmp1,tmp2; int len; while(scanf("%d",&n)!=EOF&&n!=-1){ mp.clear(); init(); cnt=0; cin>>st>>end; mp[st]=++cnt; if(st!=end) mp[end]=++cnt; for(int i=0;i<n;i++){ cin>>tmp1>>tmp2>>len; if(mp[tmp1]==0) mp[tmp1]=++cnt; if(mp[tmp2]==0) mp[tmp2]=++cnt; if(Map[mp[tmp1]][mp[tmp2]]>len){ //判断重边 Map[mp[tmp1]][mp[tmp2]]=len; Map[mp[tmp2]][mp[tmp1]]=len; } } for(int k=1;k<=cnt;k++){ for(int i=1;i<=cnt;i++){ for(int j=1;j<=cnt;j++){ if(Map[i][j]>Map[i][k]+Map[k][j]) Map[i][j]=Map[i][k]+Map[k][j]; } } } if(st==end) printf("0\n"); else if(Map[1][2]>=INF) printf("-1\n"); else printf("%d\n",Map[1][2]); } return 0; }