一、题目链接
二、题目分析
(一)算法标签
最小生成树 Kruskal
(二)解题思路
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10, M = 2e5 + 10, INF = 0x3f3f3f3f;
int n, m;
int a, b, w;
int p[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void merge(int a, int b)
{
a = find(a), b = find(b);
p[a] = b;
}
struct Edge {
int a, b, w;
bool operator< (const Edge& e) const
{
return w < e.w;
}
}edges[M];
int kruskal()
{
sort(edges, edges + m);
int cnt = 0, res = 0;
for (int i = 0; i < m; i ++ )
{
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
if (find(a) != find(b))
{
merge(a, b);
cnt ++;
res += w;
}
}
if (cnt < n - 1) return INF;
return res;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i ++ )
{
scanf("%d%d%d", &a, &b, &w);
edges[i] = {a, b, w};
}
for (int i = 1; i <= n; i ++ ) p[i] = i;
int t = kruskal();
if (t == INF) puts("impossible");
else cout << t << endl;
return 0;
}