繁忙的都市.java 1.7 KB
Newer Older
qq_36480062's avatar
c  
qq_36480062 已提交
1 2 3 4 5 6
package graph.最小生成树;

import java.util.PriorityQueue;
import java.util.Scanner;

/**
qq_36480062's avatar
c  
qq_36480062 已提交
7
 * https://blog.csdn.net/qq_30277239/article/details/107899568
qq_36480062's avatar
c  
qq_36480062 已提交
8
 * 求出无向图最小生成树中,最长边权的最小值
qq_36480062's avatar
c  
qq_36480062 已提交
9
 * 最小生成树的权值最大的边,对应Kruskal就是最后取到的那条边
qq_36480062's avatar
c  
qq_36480062 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
 */
public class 繁忙的都市 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < par.length; i++) {
            par[i] = i;
        }
        n = sc.nextInt();
        m = sc.nextInt();
        PriorityQueue<node> q = new PriorityQueue<node>();

        for (int i = 0; i < m; i++) {
            q.add(new node(sc.nextInt(), sc.nextInt(), sc.nextInt()));
        }
        int ans = 0;
        while (!q.isEmpty()) {
            node p = q.poll();
            if (!is(p.x, p.y)) {
                union(p.x, p.y);
                ans = p.w;
            }
        }
qq_36480062's avatar
c  
qq_36480062 已提交
32
        System.out.println(n - 1 + " " + ans);
qq_36480062's avatar
c  
qq_36480062 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    }

    static void union(int x, int y) {
        int xroot = find(x);
        int yroot = find(y);
        if (yroot != xroot) par[xroot] = yroot;
    }

    static boolean is(int x, int y) {
        return find(x) == find(y);
    }

    static int find(int x) {
        while (x != par[x]) {
            par[x] = par[par[x]];
            x = par[x];
        }
        return x;
    }

    static int[] par = new int[1010];

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

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

        @Override
        public int compareTo(node node) {
            return w - node.w;
        }
    }

    static int n, m;

}