中文题:http://acm.hdu.edu.cn/showproblem.php?pid=2112
思路:给地名编号,套dijstra,注意图是无向图。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
map<string,int> mp;//编号
const int INF = 1<<30;
int d[maxn],vis[maxn];
struct node
{
int d;//距离
int x;//点的编号
bool operator < (const node a)
{
return d>a.d;
}
};
struct edge
{
int from,to;
int w;
};
priority_queue<node> q;
vector<edge> e;
vector<int> g[maxn];
void addedge(int from,int to,int w)
{
edge t={from,to,w};
e.push_back(t);
edge t2={to,from,w};
e.push_back(t2);
int m=e.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
void dijstra(int s,int n)
{
while(!q.empty())q.pop();
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)d[i]=INF;
d[s]=0;
node a={0,s};
q.push(a);
while(!q.empty())
{
node temp=q.top();q.pop();
int u=temp.x;
if(vis[u])continue;
vis[u]=1;
// printf("%d ",u);
for(int i=0;i<g[u].size();i++)
{
int v=e[g[u][i]].to;
int w=e[g[u][i]].w;
if(d[v]>d[u]+w)
{
d[v]=d[u]+w;
q.push((node){d[v],v});
}
}
}
}
int main()
{
int m,n=0;
// freopen("in.txt","r",stdin);
while(scanf("%d",&m)&&m!=-1)
{
e.clear();
mp.clear();
for(int i=0;i<n;i++)g[i].clear();
n=0;
int flag=0;
string s1,s2;
cin>>s1>>s2;
mp[s1]=n++;
mp[s2]=n++;
if(s1==s2)
flag=1;
for(int i=0;i<m;i++)
{
int d;
cin>>s1>>s2>>d;
if(mp.count(s1)==0)mp[s1]=n++;
if(mp.count(s2)==0)mp[s2]=n++;
addedge(mp[s1],mp[s2],d);
}
dijstra(0,n);
if(flag)printf("0\n");
else if(d[1]==INF)printf("-1\n");
else printf("%d\n",d[1]);
}
}