1 条题解
-
0
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MAXN = 2000; const int MAXM = 10000; int n, m; // n个点 m条边 struct Edge { int u, v, w; }; Edge e[MAXM + 5]; int eCnt; bool cmp(Edge a, Edge b) { return a.w < b.w; } int fa[MAXN + 5]; int findFa(int x) { if (x == fa[x]) return x; return fa[x] = findFa(fa[x]); } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> n >> m; // 并查集初始化 for (int i = 1; i <= n; i++) fa[i] = i; int ans = 0; eCnt = 0; for (int i = 1; i <= m; i++) { int u, v, w, p; cin >> p >> u >> v >> w; if (p == 1) { int faU = findFa(u); int faV = findFa(v); fa[faU] = faV; ans += w; } else { ++eCnt; e[eCnt].u = u; e[eCnt].v = v; e[eCnt].w = w; } } m = eCnt; // 排序 sort(e + 1, e + m + 1, cmp); // kruskal/避开环 for (int i = 1; i <= m; i++) { // e[i].u <-> e[i].v : e[i].w // 如果会构成环,就不选,否则就选 int faU = findFa(e[i].u); int faV = findFa(e[i].v); if (faU != faV) { fa[faU] = faV; ans += e[i].w; } } cout << ans << "\n"; return 0; }
- 1
信息
- ID
- 622
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 4
- 标签
- (无)
- 递交数
- 48
- 已通过
- 22
- 上传者