6 9 2 4 11 3 5 13 4 6 3 5 6 4 2 3 6 4 5 7 1 2 1 3 4 9 1 3 2 // 输出 19
package com.company; import java.io.FileInputStream; import java.text.CollationKey; import java.text.Collator; import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; // 最小生成树,并查集,快速排序, 啊哈 镖局运镖 public class Solution15 { static Edge[] edges; static int[] sets; public static void main(String[] args) throws Exception{ System.setIn(new FileInputStream("D:/data.txt")); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); edges = new Edge[m]; int ans = 0; for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int w = sc.nextInt(); edges[i] = new Edge(a,b,w); } //快排 // quickSort(0, m-1); // api Arrays.sort(edges, new Comparator<Edge>() { @Override public int compare(Edge o1, Edge o2) { return o1.w-o2.w; } }); init(n); int cnt = 0; for (int i = 0; i < m; i++) { if(!connector(edges[i].a, edges[i].b)) { union(edges[i].a, edges[i].b); ans+=edges[i].w; cnt++; if(cnt == n-1) break; } } System.out.println(ans); } private static void init(int n) { sets = new int[n+1]; for (int i = 0; i <= n; i++) { sets[i] = i; } } private static int find(int n) { // 路径压缩 if(sets[n] == n) return n; return sets[n] = find(sets[n]); } private static void union(int a, int b) { int A = find(a); int B = find(b); if(A != B) sets[A] = B; } private static boolean connector(int a, int b) { return find(a) == find(b); } private static void quickSort(int left, int right) { if(left > right) return; int i = left, j = right, base = edges[left].w; while (i != j) { while (edges[j].w >= base && i < j) j--; while (edges[i].w <= base && i < j) i++; if(i < j) { Edge edge = edges[i]; edges[i] = edges[j]; edges[j] = edge; } } Edge tem = edges[left]; edges[left] = edges[j]; edges[j] = tem; quickSort(left, j-1); quickSort(j+1, right); } static class Edge { int a; int b; int w; public Edge() { } public Edge(int a, int b, int w) { this.a = a; this.b = b; this.w = w; } } }
标签:java,int,查集,edges,啊哈,new,sc,import,排序 From: https://www.cnblogs.com/ives-xu/p/16859960.html