c++编写prim算法
时间: 2023-12-18 10:28:37 浏览: 67
以下是C++编写prim算法的示例代码:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
struct Edge {
int to, w;
Edge(int to, int w) : to(to), w(w) {}
};
vector<Edge> G[MAXN];
int d[MAXN];
bool vis[MAXN];
void prim(int s) {
memset(d, INF, sizeof(d));
memset(vis, false, sizeof(vis));
d[s] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
q.push(make_pair(0, s));
while (!q.empty()) {
int u = q.top().second;
q.pop();
if (vis[u]) continue;
vis[u] = true;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].to;
int w = G[u][i].w;
if (!vis[v] && w < d[v]) {
d[v] = w;
q.push(make_pair(d[v], v));
}
}
}
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].push_back(Edge(v, w));
G[v].push_back(Edge(u, w));
}
prim(1);
int ans = 0;
for (int i = 1; i <= n; i++) {
if (d[i] == INF) {
cout << "No Answer" << endl;
return 0;
}
ans += d[i];
}
cout << ans << endl;
return 0;
}
```
阅读全文