You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.0 KiB

#include <bits/stdc++.h>
using namespace std;
const int N = 2010, M = 10010;
int n, m, p[N];
struct Edge {
int a, b, c;
bool operator<(const Edge &t) const {
return c < t.c;
}
} edge[M];
int el;
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int res;
int main() {
cin >> n >> m;
// 初始化并查集
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 0; i < m; i++) {
int a, b, c, t;
cin >> t >> a >> b >> c;
if (t == 1) // 必选的加入到同一个并查集
p[find(a)] = find(b), res += c;
else
// 记录可选边有哪些
edge[el++] = {a, b, c};
}
// 对可选边进行由小到大排序
sort(edge, edge + el);
// 枚举每条可选边
for (int i = 0; i < el; i++) {
int a = find(edge[i].a), b = find(edge[i].b), c = edge[i].c;
if (a != b) p[a] = b, res += c;
}
// 输出最短长度
cout << res << endl;
return 0;
}