大意就是求出两个地点的最短路。
简单的单源最短路问题,我用的是优先队列实现的dijkstra算法,离散数学教的~注意题目的陷阱,输入数据的坑就好啦。
#include <iostream>
#include <map>
#include <vector>
#include <queue>
#define MAXN 205
#define INF 100000000
using namespace std;
int d[MAXN];
class cmp
{
public:
bool operator()(const int &a, const int &b) const {return d[a] > d[b];} //优先队列
};
int dijkstra(int a, int b, vector<int> *v, vector<int> *w)
{
int i, j;
priority_queue<int, vector<int>, cmp> q;
for (i = 0; i < MAXN; ++i) d[i] = (i == a) ? 0 : INF;
q.push(a);
while (!q.empty())
{
j = q.top();
q.pop();
for (i = 0; i < v[j].size(); ++i)
{
int t = v[j][i];
if (d[t] > d[j] + w[j][i])
{
d[t] = d[j] + w[j][i];//更新最短路
q.push(t);
}
}
}
if (d[b] != INF) return d[b];
return -1;
}
int main()
{
int t;
cin >> t;
while (t --)
{
int n, i = 1, j, dis;
string x, y;
vector<int> v[MAXN], w[MAXN];//vector实现邻接表储存图
map<string, int> p;
cin >> n;
while (n --)
{
cin >> x >> y >> dis;//输入数据的处理
if (!p.count(x)) p[x] = i++;
if (!p.count(y)) p[y] = i++;
v[p[x]].push_back(p[y]);
w[p[x]].push_back(dis);
v[p[y]].push_back(p[x]);
w[p[y]].push_back(dis);
}
cin >> x >> y;
if ( x == y ) cout << 0 << endl; //题目陷阱
else if ( !p[x] || !p[y] ) cout << -1 << endl;
else cout << dijkstra(p[x], p[y], v, w) << endl;
}
return 0;
}