最小生成树管道铺设c++代码
时间: 2023-11-20 08:58:53 浏览: 73
根据提供的引用内容,以下是使用C++实现Prim算法和Kruskal算法求解最小生成树的代码:
1. Prim算法
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int N = 510;
int g[N][N], dist[N];
bool st[N];
int prim(int n)
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
for (int i = 0; i < n; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1 || dist[t] > dist[j]))
t = j;
if (i && dist[t] == 0x3f3f3f3f) return -1;
if (i) res += dist[t];
st[t] = true;
for (int j = 1; j <= n; j++) dist[j] = min(dist[j], g[t][j]);
}
return res;
}
int main()
{
int n, m;
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while (m--)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
}
int t = prim(n);
if (t == -1) puts("impossible");
else cout << t << endl;
return 0;
}
```
2. Kruskal算法
```c++
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 200010;
int p[N];
struct Edge
{
int a, b, w;
bool operator< (const Edge &W) const
{
return w < W.w;
}
}edges[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++)
cin >> edges[i].a >> edges[i].b >> edges[i].w;
sort(edges, edges + m);
for (int i = 1; i <= n; i++) p[i] = i;
int res = 0, cnt = 0;
for (int i = 0; i < m; i++)
{
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
a = find(a), b = find(b);
if (a != b)
{
p[a] = b;
res += w;
cnt++;
}
}
if (cnt < n - 1) puts("impossible");
else cout << res << endl;
return 0;
}
```
阅读全文