for (int i = 0; i < n; ++i) for (auto edge : edges) { int from = edge[0], to = edge[1], weight = edge[2]; if (distance[from] != INT_MAX) { distance[to] = min(distance[to], distance[from] + weight); } }
// 构建并查集 voidbuild(int n){ for (int i = 0; i <= n; ++i) father.push_back(i); } // 查询并查集 intfind(int x){ if (x != father[x]) father[x] = find(father[x]); return father[x]; } // 合并 void _union(int x, int y, int w) { int fx = find(x), fy = find(y); if (fx != fy) { father[fy] = fx; ans += w; } }
intmain(){ int N, M; cin >> N >> M; vector<vector<int>> edge; for (int i = 0; i < M; ++i) { int from, to, weight; cin >> from >> to >> weight; edge.push_back({ from, to, weight }); } auto cmp = [](vector<int>& a, vector<int>& b) -> bool{ return a[2] < b[2]; }; // 根据权值排序 sort(edge.begin(), edge.end(), cmp); build(N); for (auto e : edge) { int from = e[0], to = e[1], w = e[2]; // 如果不成环 则合并 if (find(from) != find(to)) { _union(from, to, w); cnt++; } // 如果成环 则跳过 } if (cnt == N-1) cout << ans; else cout << "orz"; return0; }
intmain(){ // 建图 int N, M; cin >> N >> M; vector<vector<vector<int>>> graph(N + 1); for (int i = 0; i < M; ++i) { int from, to, weight; cin >> from >> to >> weight; graph[from].push_back({ to, weight }); graph[to].push_back({ from, weight }); }
// 开始 Prim 算法 vector<bool> visited(N + 1, false); int ans = 0, cnt = 1;
auto cmp = [](vector<int>& a, vector<int>& b)-> bool { return a[1] > b[1]; // 使用小根堆 }; priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> q(cmp); for (auto i : graph[1]) q.push(i); visited[1] = true;
while (!q.empty()) { vector<int> cur = q.top(); q.pop(); int from = cur[0], weight = cur[1];
if (visited[from]) continue; visited[from] = true; ans += weight; // 累加当前边的权重 cnt++;