Initial commit: C++ courseware
This commit is contained in:
commit
4a4ee7c287
1789 files changed
+373489
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// 教材例 10-1 / 洛谷 P3371:非负边权单源最短路。
|
||||
// 输入 n m s,随后 m 行 u v w;有向边,可含重边和零权边。
|
||||
#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, s;
|
||||
if (!(cin >> n >> m >> s)) return 0;
|
||||
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;
|
||||
dis[s] = 0;
|
||||
q.push({0, s});
|
||||
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]) {
|
||||
int v = e.to;
|
||||
ll nd = d + e.w;
|
||||
if (nd < dis[v]) {
|
||||
dis[v] = nd;
|
||||
q.push({nd, v});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int i = 1; i <= n; ++i)
|
||||
cout << (dis[i] == INF ? 2147483647LL : dis[i])
|
||||
<< (i == n ? '\n' : ' ');
|
||||
}
|
||||
Reference in new issue
Block a user