hdu1233还是畅通工程
首先按每两个村庄的距离从小到大排序,因为最小距离的那条道路是必建造的; 每输入两个数,看他俩的老大是否一样,如果一样的话,说明这两已经连通了,不需要建造了,反之则建造。
import java.util.Arrays; import java.util.Scanner; public class hdu1233 { public static void main(String[] args) { // TODO 自动生成的方法存根 Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int n = sc.nextInt(); if (n==0) { break; } int[] lda = new int[n+1]; for (int i = 0; i < lda.length; i++) { lda[i] = i; } n = n*(n-1)/2; Node4[] aa = new Node4[n]; for (int i = 0; i < n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); aa[i] = new Node4(a, b, c); } Arrays.sort(aa,0,n); int res = 0; for (int i = 0; i < n; i++) { int x = find(aa[i].x, lda); int y = find(aa[i].y, lda); if (x != y) { lda[x] = y; res += aa[i].z; } } System.out.println(res); } sc.close(); } //找老大 public static int find(int x,int[] lda) { int index = x; while (lda[index]!=index) { index = lda[index]; } return index; } } class Node4 implements Comparable<Node4>{ public int x; public int y; public int z; Node4(int x,int y,int z) { this.x = x; this.y = y; this.z = z; } @Override public int compareTo(Node4 o) { // TODO 自动生成的方法存根 //按照z从小到大排列 return this.z - o.z; } }