Description
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.
The distance between any two farms will not exceed 100,000.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
6
0 6 1 5 100 100
6 0 5 100 3 100
1 5 0 5 6 4
5 100 5 0 100 2
100 3 6 100 0 6
100 100 4 2 6 0
15
思路:
prim算法来自算法导论
![c10ba42b3ee0a90ac290ba0e78469254.png](https://i-blog.csdnimg.cn/blog_migrate/dd026178c98d453abd4e70893a786a3c.jpeg)
核心:每一步都在连接集合A和A之外的结点的所有边中,选择一条轻量级边加入A,最终A中的边构成一棵最小生成树。因此集合A代表着最小生成树MST(mininum spanning tree)。
![9818d472d79b579b013d32b32a281bbc.png](https://i-blog.csdnimg.cn/blog_migrate/a48009f75718028d2f82ba56115fdb5a.jpeg)
#include
总结说明:
prim算法适合稠密图,边比较多的情况,因为它是按节点加入集合A。因此此处用二维数组表示图,而稀疏图用二维数组表示比较浪费空间(有大量0边权存在);
krustal算法适合稀疏图,边比较少的情况,因为它要对对边升序排序并用并查集,边少的情况比较好,因此在https://zhuanlan.zhihu.com/p/215387133 采用结构体表示图。