hdu1233还是畅通工程

首先按每两个村庄的距离从小到大排序,因为最小距离的那条道路是必建造的; 每输入两个数,看他俩的老大是否一样,如果一样的话,说明这两已经连通了,不需要建造了,反之则建造。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
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;
    }
}

  

posted @   XiaohuangTX  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示