解题报告:同朴素的 O ( n 2 ) O(n^2) O(n2)写法一样,也能够记录路径,要在松弛的阶段用一个数组保存前缀节点。关于堆优化写法的注意事项:
- 更新的时候注意那个三角不等式的意思是:我当前的最短路为dist[u],它加上新节点的w能够比源点到它的原本距离,这个w不要写成u弹出的那个节点的w!
Code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = (int)1e3+5;
const int inf = 0x3f3f3f3f;
struct Node {
int to;
int w;
Node(int to, int w) {
this->to = to;
this->w = w;
}
bool operator < (const Node& A) const {
return w > A.w;
}
};
int n,m,start,goal;
bool used[maxn]; //是否跟新过
int dist[maxn];
vector<Node> tab[maxn];
priority_queue<Node> pq;
void init() {
for (int i = 1; i <= n; i++) {
tab[i].clear();
}
int u,v,w;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
tab[v].push_back(Node(u, w));
}
}
void dijkstra() {
memset(used, false, sizeof(used));
fill(dist+1, dist+1+n, inf);
while (!pq.empty()) {
pq.pop();
}
dist[start] = 0;
pq.push(Node(start, 0));
while (!pq.empty()) {
Node x = pq.top();
pq.pop();
int u = x.to;
if (used[u]) continue;
used[u] = true;
for (int i = 0; i < tab[u].size(); i++) {
int v = tab[u][i].to;
int w = tab[u][i].w;
if (!used[v] && dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
pq.push(Node(v, dist[v]));
}
}
}
}
int main() {
int w, ans, k;
while (~scanf("%d%d%d", &n, &m, &start)) {
init();
dijkstra();
scanf("%d", &w);
ans = -1;
for (int i = 0; i < w; i++) {
scanf("%d", &k);
if (ans == -1 || ans > dist[k]) ans = dist[k];
}
printf("%d\n", ans == inf ? -1 : ans);
}
return 0;
}