请帮我把这段代码转换为c++INF = float('inf')while True: try: n, e = map(int, input().split()) edges = [[INF] * n for _ in range(n)] for _ in range(e): a, b, c = map(int, input().split()) edges[a][b] = edges[b][a] = c # Prim algorithm dist = [INF] * n dist[0] = 0 visited = [False] * n for _ in range(n): # find the vertex with minimum distance u = -1 for v in range(n): if not visited[v] and (u == -1 or dist[v] < dist[u]): u = v visited[u] = True # update distance for v in range(n): if not visited[v]: dist[v] = min(dist[v], edges[u][v]) ans = 0 min_sum = INF for i in range(n): sum_dist = sum(edges[i]) if sum_dist < min_sum: min_sum = sum_dist ans = i print(ans) except EOFError: break
时间: 2023-12-02 10:06:22 浏览: 62
下面是将该 Python 代码转换为 C++ 代码的结果:
```cpp
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
const float INF = numeric_limits<float>::infinity();
int main() {
while (true) {
try {
int n, e;
cin >> n >> e;
vector<vector<float>> edges(n, vector<float>(n, INF));
for (int i = 0; i < e; ++i) {
int a, b, c;
cin >> a >> b >> c;
edges[a][b] = edges[b][a] = c;
}
// Prim algorithm
vector<float> dist(n, INF);
dist[0] = 0;
vector<bool> visited(n, false);
for (int i = 0; i < n; ++i) {
// find the vertex with minimum distance
int u = -1;
for (int v = 0; v < n; ++v) {
if (!visited[v] && (u == -1 || dist[v] < dist[u])) {
u = v;
}
}
visited[u] = true;
// update distance
for (int v = 0; v < n; ++v) {
if (!visited[v]) {
dist[v] = min(dist[v], edges[u][v]);
}
}
}
int ans = 0;
float min_sum = INF;
for (int i = 0; i < n; ++i) {
float sum_dist = 0;
for (int j = 0; j < n; ++j) {
sum_dist += edges[i][j];
}
if (sum_dist < min_sum) {
min_sum = sum_dist;
ans = i;
}
}
cout << ans << endl;
} catch (const exception& e) {
break;
}
}
return 0;
}
```
阅读全文