首页 > 代码库 > Agri-Net POJ - 1258
Agri-Net POJ - 1258
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
Output
Sample Input
4 0 4 9 21 4 0 8 17 9 8 0 16 21 17 16 0
Sample Output
28
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 7 const int maxn=10005; 8 9 struct edge{ 10 int u,v,cost; 11 bool operator<(const edge& i)const{ 12 return cost<i.cost; 13 } 14 }es[maxn]; 15 16 int n,cnt; 17 int F[maxn],map[101][101]; 18 19 int Find(int a){ 20 if(a!=F[a]) F[a]=Find(F[a]); 21 return F[a]; 22 } 23 24 bool unite(int a,int b){ 25 int x=Find(a),y=Find(b); 26 if(x!=y) { F[x]=y; return true; } 27 else return false; 28 } 29 30 int Kruskal(){ 31 sort(es,es+cnt); 32 int ans=0; 33 for(int i=0;i<cnt;i++){ 34 edge e=es[i]; 35 if(unite(e.u,e.v)) ans=ans+e.cost; 36 } 37 return ans; 38 } 39 40 int main() 41 { while(cin>>n){ 42 cnt=0; 43 for(int i=0;i<n;i++){ 44 for(int j=0;j<n;j++){ 45 scanf("%d",&map[i][j]); 46 es[cnt].u=i; 47 es[cnt].v=j; 48 es[cnt].cost=map[i][j]; 49 cnt++; 50 } 51 } 52 for(int i=0;i<n;i++) F[i]=i; 53 cout<<Kruskal()<<endl; 54 } 55 return 0; 56 }
Agri-Net POJ - 1258