Agri-Net poj 1258
WA了好多次,注意语言和数据范围
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
题目大意:一个人当村长,想共享光纤,输入的是图,求最小生成树;
思路: 按无向图处理;
1.图转化成点到点的距离并储存起来
2.按权有小到大排序
3.Kruskal算法+并查集 构建最小生成树
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<stdlib.h> 3 struct node 4 { 5 int i,j; 6 int weight; 7 } s[5500]; 8 int cmp(const void*a,const void *b) 9 { 10 return (*(node*)a).weight-(*(node*)b).weight; 11 } 12 int v[105]; 13 int findl(int n) 14 { 15 return v[n]==n?n:findl(v[n]); 16 } 17 int main() 18 { 19 int n,i,j,k,a,sum; 20 while(~scanf("%d",&n)) 21 { 22 n++,k=0,sum=0; 23 for(i=0; i<105; i++) 24 v[i]=i; 25 for(i=1; i<n; i++) 26 { 27 for(j=1; j<n; j++) 28 { 29 scanf("%d",&a); 30 if(j>i)//0及以下的数字直接忽略 31 { 32 s[k].weight=a; 33 s[k].i=i,s[k].j=j,k++; 34 } 35 } 36 } 37 qsort(s,k,sizeof(node),cmp);//按权值从小到大排序 38 for(i=0; i<k; i++) 39 { 40 if(findl(s[i].i)!=findl(s[i].j))//简单的并查集 41 { 42 sum+=s[i].weight; 43 v[findl(s[i].i)]=s[i].j; 44 } 45 } 46 printf("%d\n",sum); 47 } 48 return 0; 49 }