HDU1233 还是畅通工程 (kruskal)

Problem

还是克鲁斯卡尔,挺顺利的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static int N = 110, M = 25010, n, cnt;
    static int p[];
    static Pair road[];

    public static void init() {
        p = new int[N];
        road = new Pair[M];
        cnt = 0;
        for (int i = 0; i < N; i++) p[i] = i;
    }

    public static void main(String[] args) throws IOException {
        while (true) {
            n = Integer.parseInt(br.readLine());
            if (n == 0) break;
            init();
            for (int i = 0; i < n * (n - 1) >> 1; i++) {
                String s[] = br.readLine().split(" ");
                int a = Integer.parseInt(s[0]);
                int b = Integer.parseInt(s[1]);
                int c = Integer.parseInt(s[2]);
                road[i] = new Pair(a, b, c);
            }

            Arrays.sort(road, 0, n * (n - 1) >> 1);

            int res = 0;
            for (int i = 0; i < n * (n - 1) >> 1; i++) {
                int x =  road[i].x;
                int y =  road[i].y;
                double w = road[i].w;
                x = find(x);
                y = find(y);
                if (x != y) {
                    p[x] = y;
                    res += w;
                    cnt++;
                }
            }
            System.out.println(res);
        }
    }

    public static int find(int x) {
        if (p[x] != x) p[x] = find(p[x]);
        return p[x];
    }
}


class Pair implements Comparable<Pair> {
   int x, y, w;

    public Pair(int x, int y, int w) {
        this.x = x;
        this.y = y;
        this.w = w;
    }

    @Override
    public int compareTo(Pair pair) {
        return this.w - pair.w;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值