parent
acf9cb1d3d
commit
ae40ca4f4d
@ -1,44 +1,58 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
const int N = 110, M = 210;
|
||||
int n, m, fa[N];
|
||||
const int INF = 0x3f3f3f3f;
|
||||
|
||||
//结构体
|
||||
struct Edge {
|
||||
int a, b, w;
|
||||
bool operator<(const Edge &t) {
|
||||
return w < t.w;
|
||||
int n, m; // n条顶点,m条边
|
||||
int res; // 最小生成树的权值和
|
||||
int cnt; // 最小生成树的结点数
|
||||
|
||||
// Kruskal用到的结构体
|
||||
struct Node {
|
||||
int a, b, c;
|
||||
bool const operator<(const Node &t) const {
|
||||
return c < t.c; // 边权小的在前
|
||||
}
|
||||
} e[M];
|
||||
} edge[M]; // 数组长度为是边数
|
||||
|
||||
//并查集
|
||||
// 并查集
|
||||
int p[N];
|
||||
int find(int x) {
|
||||
if (fa[x] != x) fa[x] = find(fa[x]); //路径压缩
|
||||
return fa[x];
|
||||
if (p[x] != x) p[x] = find(p[x]);
|
||||
return p[x];
|
||||
}
|
||||
|
||||
// Kruskal算法
|
||||
int kruskal() {
|
||||
// 1、按边权由小到大排序
|
||||
sort(edge, edge + m);
|
||||
// 2、并查集初始化
|
||||
for (int i = 1; i <= n; i++) p[i] = i;
|
||||
// 3、迭代m次
|
||||
for (int i = 0; i < m; i++) {
|
||||
int a = edge[i].a, b = edge[i].b, c = edge[i].c;
|
||||
a = find(a), b = find(b);
|
||||
if (a != b)
|
||||
p[a] = b, res += c, cnt++; // cnt是指已经连接上边的数量
|
||||
}
|
||||
// 4、特判是不是不连通
|
||||
if (cnt < n - 1) return INF;
|
||||
return res;
|
||||
}
|
||||
|
||||
int main() {
|
||||
cin >> n >> m;
|
||||
|
||||
//并查集初始化
|
||||
for (int i = 1; i <= n; i++) fa[i] = i;
|
||||
|
||||
int sum = 0;
|
||||
// Kruskal算法直接记录结构体
|
||||
for (int i = 0; i < m; i++) {
|
||||
int a, b, c;
|
||||
cin >> a >> b >> c;
|
||||
e[i] = {a, b, c};
|
||||
edge[i] = {a, b, c};
|
||||
sum += c;
|
||||
}
|
||||
sort(e, e + m); //不要忘记e数组的长度是边的数量
|
||||
|
||||
int res = 0;
|
||||
//枚举每条边
|
||||
for (int i = 0; i < m; i++) {
|
||||
int a = find(e[i].a), b = find(e[i].b), c = e[i].w;
|
||||
if (a != b)
|
||||
fa[a] = b;
|
||||
else
|
||||
res += c; //去掉的边权
|
||||
}
|
||||
printf("%d\n", res);
|
||||
int t = kruskal();
|
||||
printf("%d\n", sum - t);
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in new issue