AGRI--NET问题(prim算法求最小生成树)

Agri-Net

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 20000/10000K (Java/Other)
Total Submission(s) : 9   Accepted Submission(s) : 8
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. 
 

 

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以及n行数据,分别代表农场数目以及各农场之间的距离,求出所用网线的最小长度。

思路:明显是最小生成树问题,本例中用的prim算法(贪心思想)。

 

代码如下:

 1 #include <iostream>
 2 using namespace std;
 3 int a[101][101];
 4 int n;
 5 
 6 int prim()
 7 {
 8     int s=1;
 9     int pr=0,min1;
10     int mi[101];
11     int point,m=1;
12     int visit[101]= {0};
13     visit[1]=1;
14 
15     for(int i=1; i<=n; i++)
16         mi[i]=100001;
17 
18     while(m!=n)
19     {
20         int min1=100001;
21         for(int i=2; i<=n; i++)
22         {
23             if(!visit[i]&&mi[i]>a[s][i])
24                 mi[i]=a[s][i];
25             if(!visit[i]&&min1>mi[i])
26             {
27                 min1=mi[i];
28                 point=i;
29             }
30         }
31 
32         s=point;
33         visit[s]=1;
34         pr+=min1;
35         m++;
36     }
37     return pr;
38 }
39 
40 int main()
41 {
42     while(cin>>n)
43     {
44         for(int i=1; i<=n; i++)
45             for(int j=1; j<=n; j++)
46                 cin>>a[i][j];
47         cout<<prim()<<endl;
48     }
49     return 0;
50 }

 

 

posted on 2013-09-12 16:31  平心静气  阅读(264)  评论(0)    收藏  举报

导航