题目链接
思路
- 首先输入的车站名字为单词,不便于运算,因此我用一个map < string, int >容器储存信息,一个变量num给车站编号,每当车站第一次出现时,给车站编号为num,然后num+1,以便给下一个车站编号;
- 然后这是求最短路问题,因此我采用dijsktra+堆优化求解;
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <functional>
#include <queue>
#include <cstdio>
#include <map>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAX = 10000+5;
int t, s, d;
int n;
int dist[MAX];
bool vis[MAX];
map<string, int> m;
class Node {
public:
int to, w;
Node(int _to, int _w) {
to = _to;
w = _w;
}
};
struct cmp {
bool operator()(int a, int b) {
return dist[a] > dist[b];
}
};
vector<vector<Node> > v(MAX);
void dijsktra(int st, int e) {
priority_queue<int, vector<int>, cmp> pq;
dist[st] = 0;
pq.push(st);
while(!pq.empty()) {
int t = pq.top();
pq.pop();
if(t == e)
{
cout << dist[e] << endl;
return ;
}
vis[t] = false;
int s = v[t].size();
for(int i = 0; i < s; ++ i) {
int to = v[t][i].to;
int w = v[t][i].w;
if(dist[to] > dist[t] + w) {
dist[to] = dist[t] + w;
if(!vis[to])
pq.push(to);
}
}
}
cout << "-1" << endl;
}
int getNum(string s, int &num)
{
if(!m[s])
{
m[s] = num ++;
}
return m[s];
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n;
while(cin >> n&& n != -1) {
memset(dist, INF, sizeof(dist));
memset(vis, false, sizeof(vis));
int num = 1, s, e;
string str;
cin >> str;
s = getNum(str, num);
cin >> str;
e = getNum(str, num);
for(int i = 0; i < n; i ++) {
int from, to, w;
string f, t;
cin >> f >> t >> w;
from = getNum(f, num);
to = getNum(t, num);
v[from].push_back(Node(to, w));
v[to].push_back(Node(from, w));
}
dijsktra(s, e);
for(int i = 0; i <= n; i ++)
{
v[i].clear();
}
m.clear();
}
return 0;
}