6 xiasha westlake xiasha station 60 xiasha ShoppingCenterofHangZhou 30 station westlake 20 ShoppingCenterofHangZhou supermarket 10 xiasha supermarket 50 supermarket westlake 10 -1
50
思路:这道题其实也就是一道模板题,不过难就难在对字符串的处理上,要专门设计一个字符串数组来存储这些地名。然后把这些地名标记为数字。按照模板再写一遍SPFA或者DIJ就可以了。
ac代码:
#include<stdio.h>//题目就难在对字符串的问题的处理上。
#include<string.h>
#include<queue>
#define M 10010*2
#define N 220
#define INF 0x3f3f3f3f
using namespace std;
int vis[N],head[N],dis[N],n,edgenum;
char a[35],b[35],str[N][N];
struct node{
int from,to,cost,next;
}edge[M];
void init(){
edgenum=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int cost){
node E={u,v,cost,head[u]};
edge[edgenum]=E;
head[u]=edgenum++;
}
void getmap(){//直接让1当起点,2当终点 ,然后就是往这个str数组里面存地名了。
scanf("%s%s",&a,&b);
strcpy(str[1],a);
strcpy(str[2],b);
int i,x,y,cost,j,cnt=2;
init();
for(i=1;i<=n;i++){
scanf("%s%s%d",&a,&b,&cost);
for(j=1,x=INF,y=INF;j<=cnt;j++){
if(strcmp(str[j],a)==0)
x=j;
if(strcmp(str[j],b)==0)
y=j;
if(x!=INF&&y!=INF)
break;
}
if(x==INF){
x=++cnt;
strcpy(str[x],a);
}
if(y==INF){
y=++cnt;
strcpy(str[y],b);
}
add(x,y,cost);
add(y,x,cost);
}
}
void spfa(int beg){
queue<int>q;
q.push(beg);
memset(vis,0,sizeof(vis));
memset(dis,INF,sizeof(dis));
dis[beg]=0;
vis[beg]=1;
while(!q.empty()){
int i,u=q.front();
q.pop();
vis[u]=0;
for(i=head[u];i!=-1;i=edge[i].next){
int v=edge[i].to;
if(dis[v]>dis[u]+edge[i].cost){
dis[v]=dis[u]+edge[i].cost;
if(!vis[v]){
vis[v]=1;
q.push(v);
}
}
}
}
}
int main(){
while(scanf("%d",&n)!=EOF&&n!=-1){
getmap();//其实难点就在于对字符串的处理,也就是这个函数。
if(strcmp(str[1],str[2])==0){//要注意起点和终点相同的这种情况。
printf("0\n");
continue;
}
spfa(1);
if(dis[2]==INF)
printf("-1\n");
else
printf("%d\n",dis[2]);
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/gui951753/article/details/47816113