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.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#include #include using namespace std; #define maxn 110 #define inf 1<<29 int Map[maxn][maxn],vis[maxn],low[maxn]; int n; //第一種 void prim() { int Min,pos,sum=0; for(int i=1;i<=n;i++) { low[i]=Map[1][i]; vis[i]=0; } for(int i=1;i<=n;i++) { Min=inf; for(int j=1;j<=n;j++) { if(!vis[j] && low[j] Map[pos][j]) low[j]=Map[pos][j]; } } for(int i=1;i<=n;i++) sum+=low[i]; printf(%d ,sum); } /*第二種 void prim() { int Min,pos,sum=0; memset(vis,0,sizeof(vis)); vis[1]=1,pos=1; for(int i=1;i<=n;i++) { if(i!=pos) low[i]=Map[pos][i]; } for(int i=1;i Map[pos][j]) low[j]=Map[pos][j]; } } printf(%d ,sum); } */ int main() { while(~scanf(%d,&n)) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf(%d,&Map[i][j]); prim(); } return 0; }