POJ 1258 Agri-Net

Agri-Net

Time Limit: 1000MS Memory Limit: 10000K

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

思路:

最小生成树的模板题,用的kruscal的方法,需要注意的是这是多组数据。

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 2010;
const int maxm = 10010;
struct Edge {
    int u;
    int v;
    int dis;
    bool friend operator < (Edge a, Edge b) {
        return a.dis < b.dis;
    }
};
Edge edge[maxm];
int father[maxn];
int FindFather(int x) {
    int a = x;
    while (x != father[x]) x = father[x];
    while (a != father[a]) {
        int z = a;
        a = father[a];
        father[z] = x;
    }
    return x;
}
void UnionFather(int a, int b) {
    int fa = FindFather(a);
    int fb = FindFather(b);
    if (fa != fb) father[fa] = fb;
}
int main() {
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++) father[i] = i;
    for (int i = 0; i < m; i++) {
        scanf("%d %d %d", &edge[i].u, &edge[i].v, &edge[i].dis);
    }
    sort(edge, edge + m);
    int ans = 0, cnt = 0;;
    for (int i = 0; i < m; i++) {
        if (FindFather(edge[i].u) != FindFather(edge[i].v)) {
            UnionFather(edge[i].u, edge[i].v);
            ans = max(ans, edge[i].dis);
            cnt++;
            if (cnt == n - 1) break;
        }
    }
    printf("%d\n", ans);
    return 0;
}


全部评论

相关推荐

点赞 评论 收藏
分享
10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
团子请爱我一次_十月...:不是戈门,干哪来了,这就是java嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务