// P1629 / 教材例 10-3:有向正权图,题目保证任意两点互相可达。 // 输入 n m,随后 m 行 u v w;顶点从 1 编号。 #include #include #include #include #include using namespace std; using ll = long long; using State = pair; struct Edge { int to; ll w; }; vector dijkstra(const vector> &g, int s) { const ll INF = (1LL << 60); vector dis(g.size(), INF); priority_queue, greater> 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> 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 out = dijkstra(g, 1); vector back = dijkstra(rg, 1); ll ans = 0; for (int i = 2; i <= n; ++i) ans += out[i] + back[i]; cout << ans << '\n'; }