poj 1258 -- Agri-Net
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 38406 | Accepted: 15469 |
Description
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
水题一道。最小生成树。prim即可
1 /*====================================================================== 2 * Author : kevin 3 * Filename : AgriNet.cpp 4 * Creat time : 2014-07-09 15:55 5 * Description : 6 ========================================================================*/ 7 #include <iostream> 8 #include <algorithm> 9 #include <cstdio> 10 #include <cstring> 11 #include <queue> 12 #include <cmath> 13 #define clr(a,b) memset(a,b,sizeof(a)) 14 #define M 200 15 #define INF 0x7f7f7f7f 16 using namespace std; 17 int c[M][M],dis[M]; 18 int prim(int n) 19 { 20 bool vis[M]; 21 int i,j,k,sum = 0; 22 for(i = 0; i < n; i++){ 23 dis[i] = c[0][i]; 24 vis[i] = false; 25 } 26 vis[0] = true; 27 for(i = 1; i < n; i++){ 28 int _min = INF; 29 j = 0; 30 for(k = 0; k < n; k++){ 31 if(_min > dis[k] && !vis[k]){ 32 _min = dis[k]; 33 j = k; 34 } 35 } 36 vis[j] = true; 37 sum += dis[j]; 38 for(k = 0; k < n; k++){ 39 if(dis[k] > c[j][k] && !vis[k]){ 40 dis[k] = c[j][k]; 41 } 42 } 43 } 44 return sum; 45 } 46 int main() 47 { 48 int n; 49 while(scanf("%d",&n)!=EOF){ 50 clr(c,0); 51 int value; 52 for(int i = 0; i < n; i++){ 53 for(int j = 0; j <n; j++){ 54 scanf("%d",&value); 55 c[i][j] = value; 56 } 57 } 58 int ans = prim(n); 59 printf("%d\n",ans); 60 } 61 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。