分類:圖論,產生樹,Prim作者:ACShiryu時間:2011-7-29原題:http://poj.org/problem?id=1258Agri-Net
| Time Limit: 1000MS |
|
Memory Limit: 10000K |
| Total Submissions: 22796 |
|
Accepted: 8967 |
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.
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
40 4 9 214 0 8 179 8 0 1621 17 16 0
Sample Output
28
題目給出了n個農場之間的距離,先要讓這n個農場全部覆蓋網路,求所用網線的最小長度,典型的最小產生樹問題,比較簡單,因為是稠密圖,可直接用Prim演算法解,我提交1次就A了,詳情見代碼.
參考代碼:
1 /*
2 Prim演算法基本思想
3 1. 在圖G=(V, E) (V表示頂點 ,E表示邊)中,從集合V中任取一個頂點(例如取頂點v0)放入集合 U中,這時 U={v0},集合T(E)為空白。
4 2. 從v0出發尋找與U中頂點相鄰(另一頂點在V中)權值最小的邊的另一頂點v1,並使v1加入U。即U={v0,v1 },同時將該邊加入集合T(E)中。
5 3. 重複2,直到U=V為止。
6 這時T(E)中有n-1條邊,T = (U, T(E))就是一棵最小產生樹。
7 */
8 #include<iostream>
9 #include<cstdlib>
10 #include<cstdio>
11 #include<cstring>
12 #include<algorithm>
13 #include<cmath>
14 using namespace std;
15 int map[100][100];
16 int lowcost[100];
17 const int inf = (1<<20) ;
18 int main()
19 {
20 int n;
21 while ( cin >> n )
22 {
23 int i , j ;
24 for ( i = 0 ; i < n ; i ++ )
25 for ( j = 0 ; j < n ; j ++ )
26 cin >> map[i][j];
27 for ( i = 0 ; i < n ; i ++ )
28 lowcost[i]=map[0][i]; //初始化各點到集合的距離
29 int ans=0;//記錄產生樹的長度
30 for ( i = 0 ; i < n-1 ; i ++ )
31 {
32 int mindis=inf;
33 int minone;
34 for ( j = 0 ; j < n ; j ++ )
35 {//尋找到集合距離最近的點
36 if(lowcost[j]&&mindis>lowcost[j])
37 {
38 mindis=lowcost[j];
39 minone=j;
40 }
41 }
42 ans+=lowcost[minone];
43 lowcost[minone]=0;
44 for ( j = 0 ; j < n ; j ++ )
45 {//更新各點到集合的距離
46 if(lowcost[j]>map[minone][j])
47 lowcost[j]=map[minone][j];
48 }
49 }
50 cout<<ans<<endl;
51 }
52 return 0;
53 }