转载请注明该文链接
题意:给一些结点,一些无向边,给起点a终点b(字母输入),求最短距离。
思路:直接建图跑一遍SPFA。这里学习了map的一些用法。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef __int64 ll;
const int N=160;
const int M=10010;
const ll inf=1LL<<60;
struct node
{
int v;
ll dis;
node *next;
}E[M<<1],*G[N],*head;
inline void add(int a,int b,ll c,node *G[])
{
head->v=b;
head->dis=c;
head->next=G[a];
G[a]=head++;
}
int m,num;
ll d[N];
bool inq[N];
map<string,int> dict;
void init()
{
fill(d,d+N,inf);
memset(G,0,sizeof(G));
memset(inq,false,sizeof(inq));
dict.clear();
head=E;
num=0;
}
inline int change(char *s)
{
if(dict.count(s)) return dict[s];
else return dict[s]=num++;
}
void SPFA(int s,ll d[],node *G[])
{
d[s]=0;
deque<int> Q;
Q.push_front(s);
while(!Q.empty())
{
int u=Q.front();
Q.pop_front();
inq[u]=false;
for(node *p=G[u];p;p=p->next)
{
int v=p->v;
ll dis=p->dis;
if(d[v]>d[u]+dis)
{
d[v]=d[u]+dis;
if(!inq[v])
{
inq[v]=true;
if(!Q.empty() && d[v]<=d[Q.front()]) Q.push_front(v);
else Q.push_back(v);
}
}
}
}
}
int main()
{
char s1[40],s2[40];
while(scanf("%d",&m),m+1)
{
init();
int s,t;
scanf("%s %s",s1,s2);
s=change(s1),t=change(s2);
int a,b;
ll c;
for(int i=0;i<m;i++)
{
scanf("%s %s %I64d",s1,s2,&c);
a=change(s1),b=change(s2);
add(a,b,c,G);
add(b,a,c,G);
}
SPFA(s,d,G);
if(d[t]==inf) printf("-1\n");
else printf("%I64d\n",d[t]);
}
return 0;
}