题解 | #【模板】最小生成树#
【模板】最小生成树
https://www.nowcoder.com/practice/6434142fe980434899c396a6124b0778
看了看题解区做法挺全的,我给一个vec存边的prim吧
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 5e5 + 5; int __t = 1; struct Edge { int u, v, w, idx; bool operator>(const Edge& other) const { return w > other.w; } }; vector<Edge> adj[N]; int vis[N]; priority_queue<Edge, vector<Edge>, greater<Edge>> pq; void solve() { int n, m; cin >> n >> m; for (int i = 1; i <= m; ++i) { int u, v, w; cin >> u >> v >> w; adj[u].push_back({u, v, w, i}); adj[v].push_back({v, u, w, i}); } int sum = 0; vector<int> ed; pq.push({0, 1, 0, 0}); while (!pq.empty()) { Edge e = pq.top(); pq.pop(); if (vis[e.v]) continue; vis[e.v] = true; if (e.idx != 0) { sum += e.w; ed.push_back(e.idx); } for (auto next : adj[e.v]) { if (!vis[next.v]) { pq.push(next); } } } cout << sum << "\n"; for (auto x : ed) cout << x << " "; cout << "\n"; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }