47 lines
1.4 KiB
C++
47 lines
1.4 KiB
C++
// 教学扩展:非负有向图,多源最短路。
|
|
// 输入 n m r;下一行 r 个源点编号;随后 m 行 u v w。
|
|
// 顶点编号 1..n,允许重复源点;输出到各点的最近距离,不可达输出 -1。
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <queue>
|
|
#include <utility>
|
|
#include <functional>
|
|
using namespace std;
|
|
using ll = long long;
|
|
using State = pair<ll, int>;
|
|
struct Edge { int to; ll w; };
|
|
int main() {
|
|
ios::sync_with_stdio(false); cin.tie(nullptr);
|
|
int n, m, r;
|
|
if (!(cin >> n >> m >> r)) return 0;
|
|
vector<int> sources(r);
|
|
for (int &x : sources) cin >> x;
|
|
vector<vector<Edge>> g(n + 1);
|
|
for (int i = 0; i < m; ++i) {
|
|
int u, v; ll w; cin >> u >> v >> w;
|
|
g[u].push_back({v, w});
|
|
}
|
|
const ll INF = (1LL << 60);
|
|
vector<ll> dis(n + 1, INF);
|
|
priority_queue<State, vector<State>, greater<State>> q;
|
|
for (int x : sources) {
|
|
if (dis[x] == 0) continue;
|
|
dis[x] = 0;
|
|
q.push({0, x});
|
|
}
|
|
while (!q.empty()) {
|
|
State cur = q.top(); q.pop();
|
|
ll d = cur.first; int u = cur.second;
|
|
if (d != dis[u]) continue;
|
|
for (const auto &e : g[u]) {
|
|
ll nd = d + e.w;
|
|
if (nd < dis[e.to]) {
|
|
dis[e.to] = nd;
|
|
q.push({nd, e.to});
|
|
}
|
|
}
|
|
}
|
|
for (int i = 1; i <= n; ++i)
|
|
cout << (dis[i] == INF ? -1 : dis[i]) << (i == n ? '\n' : ' ');
|
|
}
|