标签:
Agri-Net
Time Limit: 1000MS |
|
Memory Limit: 10000K |
Total Submissions: 45145 |
|
Accepted: 18534 |
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
看到给的数据应该是 用prime 做比较方便 ,但闲的没事就用Kruskal写了一遍。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct node{
int u, v, w;
};
node map[11000];
int per[110], n;
int cmp(node a, node b){
return a.w < b.w;
}
void init(){
for(int i = 1; i <= n ;++i)
per[i] = i;
}
int find(int x){
if(x == per[x])
return x;
return per[x] = find(per[x]);
}
int join(int x, int y){
x = find(x);
y = find(y);
if(x != y){
per[x] = y;
return 1;
}
else
return 0;
}
int main (){
while(scanf("%d", &n) != EOF){
int k = 0;
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j){
scanf("%d", &map[++k].w);
map[k].u = i, map[k].v = j;
}
//printf("%d\n",k);
sort(map + 1, map + 1 + k, cmp);
int sum = 0;
init();
for(int i = 1 + n; i <= k; ++i){
//printf("--%d %d %d\n",map[i].u, map[i].v, map[i].w);
if(join(map[i].u, map[i].v))
sum += map[i].w;
}
printf("%d\n", sum);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
POJ 1258【最小生成树 && Kruskal && 水题】
标签:
原文地址:http://blog.csdn.net/hpuhjh/article/details/47399231