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

OJ-5G网络建设

 示例1

输入:
3
3
1 2 3 0
1 3 1 0
2 3 5 0
输出:
4

示例2

输入:
3
1
1 2 5 0
输出:
-1

示例3

输入:
3
3
1 2 3 0
1 3 1 0
2 3 5 1
输出:
1

分析:压缩路径

顺序:1 2;1 3;2 3;3 4

root[i]初始化合并1 2合并1 3合并2 3合并3 4最终root
root[1]124
root[2]234
root[3]344
root[4]44

顺序:2 3;1 2;1 3;3 4

root[i]初始化合并2 3合并1 2合并1 3合并3 4最终root
root[1]134
root[2]234
root[3]344
root[4]44

结论:优先按照边的权重小的连接,上述4个节点至少需要3条边连接,1 2,1 3,2 3中只需其中任意两条边即能将1、2、3节点连接。

代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;public class 五G网络建设2 {private static int[] root;private static final List<int[]> edge = new ArrayList<>();public static void main(String[] args) {Scanner in = new Scanner(System.in);int n = in.nextInt();int m = in.nextInt();root = new int[n + 1];for (int i = 1; i <= n; i++) {root[i] = i;}for (int i = 0; i < m; i++) {int x = in.nextInt();int y = in.nextInt();int z = in.nextInt();int p = in.nextInt();if (p == 1) {merge(x, y);} else {edge.add(new int[]{x, y, z});}}edge.sort((o1, o2) -> o1[2] - o2[2]);int price = 0;for (int[] e : edge) {if (merge(e[0], e[1]) == 1) {price += e[2];}}boolean ok = true;for (int i = 1; i <= n; i++) {if (getRoot(i) != getRoot(1)) {ok = false;break;}}if (ok) {System.out.println(price);} else {System.out.println(-1);}}private static int merge(int x, int y) {int rootX = getRoot(x);int rootY = getRoot(y);if (rootX == rootY) {return 0;}root[rootX] = rootY;return 1;}private static int getRoot(int x) {if (root[x] == x) {return x;}return getRoot(root[x]);}
}

251.【华为OD机试】5G网络建设(最小生成树算法-Java&Python&C++&JS实现)_java算法5g基站-CSDN博客

http://www.lryc.cn/news/476653.html

相关文章:

  • Linux简介
  • android——渐变色
  • MySQL约束管理
  • 拯救者y7000p 打开XMP
  • 2024 Rust现代实用教程Iterator迭代器
  • 基于SpringBoot司机信用评价的货运管理系统【附源码】
  • 使用PostgreSQL进行高效数据管理
  • 数据库条件查询排查——引号故障
  • Python爬虫:揭开淘宝商品描述的神秘面纱
  • 动态规划— 一和零
  • 【Android】SharedPreferences存储中没有 Double 类型数据存储的解决方式
  • ffmpeg:视频字幕嵌入(GPU加速)
  • DCN网络进行新冠肺炎影像分类
  • C++中的继承——第二篇
  • 动态规划探索篇
  • js中多let与var
  • 基于人工智能的搜索和推荐系统
  • 冷钱包与热钱包的差异 | 加密货币存储的安全方案
  • 014:无人机遥控器操作
  • PCL 点云高度归一化
  • 【Effective C++】阅读笔记4
  • 浅谈mysql【8.0】链接字符串
  • BERT,RoBERTa,Ernie的理解
  • 获取 Wind 数据并进行简单的择时分析
  • 小檗碱的酵母代谢工程生物合成-文献精读78
  • 文件指针和写入操作
  • 跨越科技与文化的桥梁——ROSCon China 2024 即将盛大开幕
  • springboot+shiro 权限管理
  • PureMVC在Unity中的使用(含下载链接)
  • 25国考照片处理器使用流程图解❗