#include<iostream>
#include<map>
#include<string>
#include<queue>
using namespace std;
const int MAXE = 2*10005;
const int MAXV = 205;//地名
const int inf = 10000000;
typedef struct node
{
int s, t, w, next;
} N;
map<string, int> station;
N edge[MAXE];
int arrHead[MAXV], arrDis[MAXV];
int inQue[MAXV];
int stationNum;//站点个数
int edgeNum;//边数
void init()
{
}
void SPFA(int s)
{
queue<int> Q;
for(int i = 1; i< stationNum; i++)
{
arrDis[i] = inf;
}
Q.push(s);
inQue[s] = 1;
arrDis[s] = 0;
while(!Q.empty())
{
int v = Q.front();
Q.pop();
inQue[v] = 0;
int ie;
for(ie = arrHead[v]; ie != -1; ie = edge[ie].next)
{
N e = edge[ie];
if(arrDis[e.t] > arrDis[v] + e.w)
{
arrDis[e.t] = arrDis[v] + e.w;
if(!inQue[e.t])
{
inQue[e.t] = 1;
Q.push(e.t);
}
}
}
}
}
void addedge(int u,int v,int w)
{
edgeNum++;
edge[edgeNum].s = u;
edge[edgeNum].t = v;
edge[edgeNum].w = w;
edge[edgeNum].next = arrHead[u];
arrHead[u] = edgeNum;
edgeNum++;
edge[edgeNum].s = v;
edge[edgeNum].t = u;
edge[edgeNum].w = w;
edge[edgeNum].next = arrHead[v];
arrHead[v] = edgeNum;
}
int main(void)
{
int n;//边数
while(scanf("%d", &n)!=EOF && n )
{
//记得初始化
station.clear();
memset(arrHead, -1, sizeof(arrHead));
stationNum = 3;
memset(inQue, 0, sizeof(inQue));
string start, end, begin, aim;
//输入要用cin哦
cin >> begin >> aim;
//起始站和终点站为1,2
station[begin] = 1;
station[aim] = 2;
int w;
edgeNum = 0;
for(int i=0; i<n; i++)
{
//通过staionnum映射每一个sation对应的数字点
cin >> start >> end >> w;
if(!station[start])
station[start] = stationNum++;
if(!station[end])
station[end] = stationNum++;
//建立静态邻接表
addedge(station[start],station[end],w);
}
SPFA(station[begin]);
if(arrDis[station[aim]] == inf)
{
printf("-1\n");
}
else
{
printf("%d\n", arrDis[station[aim]]);
}
}
return 0;
}
hdu2112map+spfa映射最短路
最新推荐文章于 2020-07-10 23:31:10 发布