ACM_最短网络(最小生成树)
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。
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. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.
译文:输入包括几种情况。对于每种情况,第一行包含农场的数量,N(3 <= N <= 100)。以下几行包含N×N视锥矩阵,其中每个元素显示从农场到另一个的距离。从逻辑上讲,它们是由N个空格分隔的整数组成的N行。当然,对角线将为0,因为从农场到农场的距离对这个问题并不有趣。
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 }