C++基于dfs的prim算法
时间: 2024-06-13 10:09:25 浏览: 136
基于DFS的Prim算法是一种用于生成最小生成树的算法,它使用了深度优先搜索来遍历图形,并使用优先队列来选择下一个要访问的节点。以下是C++实现基于DFS的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 used[MAXN];
void prim(int s) {
memset(d, INF, sizeof(d));
memset(used, false, sizeof(used));
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
d[s] = 0;
q.push(make_pair(0, s));
while (!q.empty()) {
pair<int, int> p = q.top();
q.pop();
int v = p.second;
if (used[v]) continue;
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
Edge e = G[v][i];
if (d[e.to] > e.w && !used[e.to]) {
d[e.to] = e.w;
q.push(make_pair(d[e.to], e.to));
}
}
}
}
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++) {
ans += d[i];
}
cout << ans << endl;
return 0;
}
```
阅读全文