import heapqdef prim(graph, start): n = len(graph) visited = [False] * n distance = [float('inf')] * n distance[start] = 0 heap = [(0, start)] while heap: _, u = heapq.heappop(heap) if visited[u]: continue visited[u] = True for v, w in graph[u]: if not visited[v] and w < distance[v]: distance[v] = w heapq.heappush(heap, (w, v)) return sum(distance)def min_distance_sum(graph): n = len(graph) min_distance = float('inf') for i in range(n): distance_sum = prim(graph, i) min_distance = min(min_distance, distance_sum) return min_distancegraph = [ [(1, 2), (2, 1)], [(0, 2), (2, 3), (3, 1)], [(0, 1), (1, 3), (3, 1)], [(1, 1), (2, 1)]]print(min_distance_sum(graph)) # 输出:4把这段代码转换成c++
时间: 2023-11-09 07:07:38 浏览: 65
以下是将 Python 代码转换为 C++ 的版本:
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
typedef pair<int, int> pii;
int prim(vector<vector<pii>>& graph, int start) {
int n = graph.size();
vector<bool> visited(n, false);
vector<int> distance(n, numeric_limits<int>::max());
distance[start] = 0;
priority_queue<pii, vector<pii>, greater<pii>> pq;
pq.push({0, start});
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
for (auto [v, w] : graph[u]) {
if (!visited[v] && w < distance[v]) {
distance[v] = w;
pq.push({w, v});
}
}
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += distance[i];
}
return sum;
}
int min_distance_sum(vector<vector<pii>>& graph) {
int n = graph.size();
int min_distance = numeric_limits<int>::max();
for (int i = 0; i < n; i++) {
int distance_sum = prim(graph, i);
min_distance = min(min_distance, distance_sum);
}
return min_distance;
}
int main() {
vector<vector<pii>> graph = {
{{1, 2}, {2, 1}},
{{0, 2}, {2, 3}, {3, 1}},
{{0, 1}, {1, 3}, {3, 1}},
{{1, 1}, {2, 1}}
};
cout << min_distance_sum(graph) << endl; // 输出:4
return 0;
}
```
阅读全文