当前位置: 首页 > news >正文

19914 最小生成树2

19914 最小生成树2

⭐️难度:中等
🌟考点:最小生成树
📖
在这里插入图片描述

📚

import java.util.*;

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

    static ArrayList<Edge> g = new ArrayList<>(); // 存边
    static int n;
    static int m;
    static class UnionSet{  // 并查集
        int[] f,sz;
        UnionSet(int n){
            f = new int[n+1];
            sz = new int[n+1];
            for (int i = 1; i <= n; i++) {
                f[i] = i;
                sz[i] = i;
            }
        }

        int find(int x){
            return f[x] == x ? x : (f[x] = find(f[x]));
        }

        void union(int x,int y){
            int fx = find(x);
            int fy = find(y);
            if(sz[fx] < sz[fy]){
                f[fx] = fy;
                sz[fy] += sz[fx];
            }else{
                f[fy] = fx;
                sz[fx] += sz[fy];
            }
        }
    }

    static boolean kruskal(){
        g.sort(Comparator.comparingInt(e ->e.w));
        UnionSet us = new UnionSet((n));
        int cnt = 0;
        int ans = 0; // 边权
        for(Edge e : g){
            if(us.find(e.u) == us.find(e.v)) continue;
            us.union(e.u,e.v);
            ans += e.w;
            if(++cnt == n-1){
                System.out.println(ans);
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < m; i++) {
            g.add(new Edge(sc.nextInt(), sc.nextInt(),sc.nextInt()));
        }
        if(!kruskal()){
            System.out.println("impossible");
        }
    }
}

相关文章:

  • 《Mycat核心技术》第21章:高可用负载均衡集群的实现(HAProxy + Keepalived + Mycat)
  • 小豆包api:gpt-4o模型api已接入,出图更稳定
  • 推荐系统(十九):优势特征蒸馏(Privileged Features Distillation)在商品推荐中的应用(二)
  • DOM 加载函数
  • 5.实现 Channel 类,Reactor 模式初步形成
  • Muduo网络库 - Buffer模块
  • Java进阶——静态代理与动态代理
  • Windows10上部署DeepSeek+RAG知识库操作详解(Dify方式)之2
  • smartdns 在企业场景中的应用心得
  • Parallel_Scheduling_of_DAGs_under_Memory_Constraints论文阅读
  • DPO vs PPO
  • 微服务架构:构建可持续演进的微服务架构的原则与实践指南
  • 计算机求职面试中高频出现的经典题目分类整理
  • Linux驱动开发 块设备
  • ESXI 安装及封装第三方驱动和在ESXI系统下安装驱动
  • VulkanSceneGraph (VSG) 开发入门
  • fastboot
  • 理解llama.cpp如何进行LLM推理
  • 2023年3月全国计算机等级考试真题(二级C语言)
  • 逆向--ARM64汇编