Description
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
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
//用prim最小生成树算法可以很容易解决
#include<iostream>
using namespace std;
void prim(int **a,int n)//一个二维数组 及 边长
{
int *select=new int [n];
memset(select,0,n*sizeof(int));
int sum=0;
int selnum=1;//已经选出的节点个数
select[0]=1;//从1开始
int smallnum;//记录最小的长度
int ir,jr;//寄存最小线段的起始点与终点
while(selnum!=n)
{smallnum=100000;
for(int i=0;i<n;i++)
{
if(select[i]!=0)
for(int j=0;j<n;j++)
{if((smallnum>a[i][j])&&(select[j]==0)) {smallnum=a[i][j];ir=i;jr=j;}}
}
select[jr]=1;
sum+=smallnum;
selnum++;
}
cout<<sum<<endl;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{ int **a=new int*[n];
for(int i=0;i<n;i++)
a[i]=new int[n];
for( i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>a[i][j];
prim(a,n);
}
return 0;
}