1 条题解
-
0
问题分析:
- 这是典型的最小生成树(MST)问题
- 需要从完全图中找出连接所有顶点的最小权重边集
- 可以使用Prim或Kruskal算法解决
关键点:
- 完全图,每个农场都与其他所有农场直接相连
- 需要找到权重和最小的连接方式
- 确保所有农场连通
解题步骤:
- 读取输入,构建邻接矩阵
- 使用Prim算法:
- 从任意顶点开始
- 每次选择连接已选集合和未选集合的最小权重边
- 直到包含所有顶点
- 计算所选边的权重和
#include <algorithm> #include <stdio.h> using namespace std; const int N = 100; int f[N + 1], fcnt; void UFInit(int n) { for(int i = 1; i <=n; i++) f[i] = i; fcnt = n; } int Find(int a) { return a == f[a] ? a : f[a] = Find(f[a]); } bool Union(int a, int b) { a = Find(a); b = Find(b); if (a != b) { f[a] = b; fcnt--; return true; } else return false; } struct Edge { int src, dest, cost; } edges[N * N]; bool cmp(Edge a, Edge b) { return a.cost < b.cost; } int main() { int n, cost, cnt2; while(~scanf("%d", &n)) { UFInit(n); cnt2 = 0; for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) { scanf("%d", &cost); if(j > i) { edges[cnt2].src = i; edges[cnt2].dest = j; edges[cnt2++].cost = cost; } } sort(edges, edges + cnt2, cmp); int ans = 0; for(int i = 0; i < cnt2; i++) { if(Union(edges[i].src, edges[i].dest)) { ans += edges[i].cost; if(fcnt == 1) break; } } printf("%d\n", ans); } return 0; }
- 1
信息
- ID
- 259
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- 递交数
- 1
- 已通过
- 1
- 上传者