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.
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
题意:给出村庄的数目和任意两个村庄之间的距离,求将这些村庄相互连通的最短路径。
题解:这是一个最小生成树的问题,因为是任意两个村庄都有路径,属于密集图,选择普里姆算法。
#include <stdio.h> #include <string.h> #define maxint 99999999 int m; int c[101][101]; void prem() { int s[101]; int dis[101]; int ans = 0; memset(s,0,sizeof(s)); int i,j; for(i = 1; i<=m; i++) dis[i] = c[1][i];//为dis初始化为从点1到点i的距离 s[1] = 1;//把点1加入到连通图中 for(i = 1; i<m; i++) { int pos,mi; mi = maxint; for(j = 1; j<=m; j++)//寻找没有加进连通图中并且 { if(!s[j] && mi > dis[j]) { pos = j;//将下标记录下来 mi = dis[j];//将距离记录下来 } } if(maxint == mi)//如果mi没有变化,也就说明所有的点都加入连通图中了。 break; s[pos] = 1;//把点pos加入连通图 ans += mi;//增加相应的距离 for(j = 1; j<=m; j++) { if(!s[j] && dis[j] > c[pos][j]) dis[j] = c[pos][j]; } } printf("%d\n",ans); } int main() { while(scanf("%d",&m)!=EOF) { int i,j; for(i = 1; i<=m; i++) { for(j = 1; j<=m; j++) { scanf("%d",&c[i][j]); if(i == j) c[i][j] = maxint;//因为prem算法是根据路径的大小选择, //所以相同点的时候,为了不被选进去,初始化为无穷大 } } prem(); } return 0; }