2573. Hub Connection plan

wangliqiang

import java.util.*;

public class Main {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int hubCount = scanner.nextInt();
    int connectCount = scanner.nextInt();

    List<Edge> edges = new ArrayList<>();
    for (int i = 0; i < connectCount; i++) {
        int u = scanner.nextInt();
        int v = scanner.nextInt();
        int w = scanner.nextInt();
        edges.add(new Edge(u, v, w));
    }

    Collections.sort(edges, new Comparator<Edge>() {
        @Override
        public int compare(Edge o1, Edge o2) {
            return o1.w - o2.w;
        }
    });

    int edgesAccepted = 0;
    long cost = 0;
    DisjSets ds = new DisjSets(hubCount);
    while (edgesAccepted < hubCount - 1) {
        Edge e = edges.remove(0);
        int uSet = ds.find(e.u - 1);
        int vSet = ds.find(e.v - 1);
        if (uSet != vSet) {
            edgesAccepted++;
            ds.union(uSet, vSet);
            cost += e.w;
        }
    }
    System.out.println(cost);
}

private static class Edge {
    int u;
    int v;
    int w;

    public Edge(int u, int v, int w) {
        this.u = u;
        this.v = v;
        this.w = w;
    }
}

public static class DisjSets {
    private int[] s;

    public DisjSets(int numElements) {
        s = new int[numElements];
        for (int i = 0; i < s.length; i++) {
            s[i] = -1;
        }
    }

    public void union(int root1, int root2) {
        s[root2] = root1;
    }

    public int find(int x) {
        if (s[x] < 0) {
            return x;
        } else {
            return find(s[x]);
        }
    }
}

}

你当前正在回复 博客/题目
存在问题!