普里姆算法和克鲁斯卡尔算法c++代码实现
时间: 2024-06-18 15:02:19 浏览: 122
普里姆算法和克鲁斯卡尔算法都是用于解决最小生成树问题的常见算法,它们的具体实现方式如下:
普里姆算法的实现方式:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e3 + 5;
struct Edge {
int to, w;
};
vector<Edge> G[MAXN];
int d[MAXN], vis[MAXN];
void Prim(int s) {
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
fill(d + 1, d + 1 + MAXN, INF);
fill(vis + 1, vis + 1 + MAXN, false);
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 (vis[v]) continue;
vis[v] = true;
for (int i = 0; i < G[v].size(); i++) {
Edge e = G[v][i];
if (d[e.to] > e.w && !vis[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++) {
if (d[i] != INF) ans += d[i];
}
cout << ans << endl;
return 0;
}
```
克鲁斯卡尔算法的实现方式:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 1e3 + 5;
struct Edge {
int u, v, w;
};
vector<Edge> edges;
int p[MAXN], r[MAXN];
bool cmp(Edge a, Edge b) {
return a.w < b.w;
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
if (r[x] < r[y]) {
p[x] = y;
} else {
p[y] = x;
if (r[x] == r[y]) r[x]++;
}
}
int kruskal(int n) {
for (int i = 1; i <= n; i++) {
p[i] = i;
r[i] = 0;
}
sort(edges.begin(), edges.end(), cmp);
int ans = 0;
for (int i = 0; i < edges.size(); i++) {
Edge e = edges[i];
if (find(e.u) != find(e.v)) {
ans += e.w;
unite(e.u, e.v);
}
}
return ans;
}
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back(Edge{u, v, w});
}
cout << kruskal(n) << endl;
return 0;
}
```
阅读全文