Problem 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.
译文:农民约翰已经当选为他镇上的市长!他的竞选承诺之一是将互联网连接到该地区的所有农场。当然,他需要你的帮助。农夫约翰为他的农场订购了高速连接,并将与其他农民分享他的连接。为了降低成本,他希望铺设最少量的光纤将他的农场与其他农场连接起来。给出连接每对农场需要多少光纤的清单,您必须找到将它们连接在一起所需的最少光纤数量。每个服务器场必须连接到其他服务器场,以便数据包可以从任何一个服务器场流向其他服务器场。任何两个农场之间的距离不会超过100,000。
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
解题思路:简单的求最小生成树,此题适合用Prim算法,水过!
AC代码之Prim算法:
1 #include<bits/stdc++.h>
2 using namespace std;
3 const int maxn = 105;
4 int n,mincost[maxn],cost[maxn][maxn];
5 bool vis[maxn];
6 int Prim(){
7 for(int i=1;i<=n;++i)
8 mincost[i]=cost[1][i];
9 mincost[1]=0;vis[1]=true;
10 int res=0;
11 for(int i=1;i<n;++i){
12 int k=-1;
13 for(int j=1;j<=n;++j)
14 if(!vis[j] && (k==-1||mincost[k]>mincost[j]))k=j;
15 if(k==-1)break;
16 vis[k]=true;
17 res+=mincost[k];
18 for(int j=1;j<=n;++j)
19 if(!vis[j])mincost[j]=min(mincost[j],cost[k][j]);
20 }
21 return res;
22 }
23 int main()
24 {
25 while(cin>>n){
26 for(int i=1;i<=n;++i)
27 for(int j=1;j<=n;++j)
28 cin>>cost[i][j];
29 memset(vis,false,sizeof(vis));
30 cout<<Prim()<<endl;
31 }
32 return 0;
33 }