Initial commit: C++ courseware
This commit is contained in:
commit
4a4ee7c287
1789 files changed
+373489
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// P1629 / 教材例 10-3:有向正权图,题目保证任意两点互相可达。
|
||||
// 输入 n m,随后 m 行 u v w;顶点从 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; };
|
||||
vector<ll> dijkstra(const vector<vector<Edge>> &g, int s) {
|
||||
const ll INF = (1LL << 60);
|
||||
vector<ll> dis(g.size(), 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]) {
|
||||
ll nd = d + e.w;
|
||||
if (nd < dis[e.to]) {
|
||||
dis[e.to] = nd;
|
||||
q.push({nd, e.to});
|
||||
}
|
||||
}
|
||||
}
|
||||
return dis;
|
||||
}
|
||||
int main() {
|
||||
ios::sync_with_stdio(false); cin.tie(nullptr);
|
||||
int n, m;
|
||||
if (!(cin >> n >> m)) return 0;
|
||||
vector<vector<Edge>> g(n + 1), rg(n + 1);
|
||||
for (int i = 0; i < m; ++i) {
|
||||
int u, v; ll w; cin >> u >> v >> w;
|
||||
g[u].push_back({v, w});
|
||||
rg[v].push_back({u, w});
|
||||
}
|
||||
vector<ll> out = dijkstra(g, 1);
|
||||
vector<ll> back = dijkstra(rg, 1);
|
||||
ll ans = 0;
|
||||
for (int i = 2; i <= n; ++i) ans += out[i] + back[i];
|
||||
cout << ans << '\n';
|
||||
}
|
||||
Reference in new issue
Block a user