Agri-Net
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11398 | Accepted: 4755 |
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.
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
这是一个关于最小生成树的题目,我现在在复习数据结构,正好看到最小生成树的知识,正好看到POJ上面的这几个题目,我就做了一下,
也复习了一下两个算法 普里姆和克鲁斯卡尔 。我是用普里姆算法写的,至于细节就不讲了,可以看我的代码:
#include<iostream>
#include<cstring>
using namespace std;
int n,d[101][101];
int v[101];
int main()
{
while(cin>>n)
{
int i,j,m,t,best=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>d[i][j];
memset(v,0,sizeof(v));
v[1]=1;
int t1=1;
while(t1<n)
{
m=111111;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(!v[i]&&v[j]&&d[i][j]<m&&d[i][j]>0)
{
//cout<<i<<" "<<j<<" "<<v[i]<<" "<<v[j]<<" ";
m=d[i][j];
t=i;
//cout<<t<<endl;
}
}
}
v[t]=1;
best+=m;
//cout<<i<<" "<<best<<endl;
t1++;
}
cout<<best<<endl;
}
return 0;
}