永夜初晗凝碧天

本博客现已全部转移到新地址,欲获取更多精彩文章,请访问http://acshiryu.github.io/

导航

POJ 1258 Agri-Net 解题报告

分类:图论,生成树,Prim
作者:ACShiryu
时间:2011-7-29
Agri-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

4
0 4 9 21
4 0 8 17
9 8 0 16
21 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 }

  

posted on 2011-07-29 11:07  ACShiryu  阅读(1207)  评论(0编辑  收藏  举报