牛客NC99 多叉树的直径【较难 深度优先 Java/Go/PHP】

embedded/2024/9/23 14:24:09/

题目

在这里插入图片描述
题目链接:
https://www.nowcoder.com/practice/a77b4f3d84bf4a7891519ffee9376df3

思路

核心就是树的最大直径(globalMax)一定是以某一个node为root最长的两个path-to-leaf.
就是普通dfs的同时算路径长度。时间: O(n), DFS一次
空间: O(n)

参考答案Java

import java.util.*;/** public class Interval {*   int start;*   int end;*   public Interval(int start, int end) {*     this.start = start;*     this.end = end;*   }* }*/public class Solution {/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 树的直径* @param n int整型 树的节点个数* @param Tree_edge Interval类一维数组 树的边* @param Edge_value int整型一维数组 边的权值* @return int整型*/public int solve (int n, Interval[] Tree_edge, int[] Edge_value) {//核心就是树的最大直径(globalMax)一定是以某一个node为root最长的两个path-to-leaf.//就是普通dfs的同时算路径长度。////时间: O(n), DFS一次//空间: O(n)// node_id -> { {nei1, cost1}, {nei2, cost2}, ... }Map<Integer, List<int[]>> graph = new HashMap<>();int[] globalMax = {0};// construct graphfor (int i = 0; i < n ; i++) {graph.put(i, new ArrayList<int[]>());}for (int i = 0; i < n - 1 ; i++) {// treat tree edge as bi-directionalint from = Tree_edge[i].start;int to = Tree_edge[i].end;graph.get(from).add(new int[] {to, Edge_value[i]});graph.get(to).add(new int[] {from, Edge_value[i]});}// 因为edge是bi-directional, 随便从哪个node开始dfs都一样。这里用了node-0.// -1 作为parentdfs(graph, globalMax, 0, -1);return globalMax[0];}// returns the max cost path-to-leaf from this root.public int dfs(Map<Integer, List<int[]>> graph, int[] ans, int root,int parent) {int maxCost = 0;int maxCost2 = 0;for (int[] nexts : graph.get(root)) {// NOTE: BaseCase (i.e. leaf) has only 1 nei, which is the parent//       thus leaf will return maxCost = 0 directly.if (nexts[0] == parent) continue;// recursively finds the max cost path to any leafint cost = dfs(graph, ans, nexts[0], root) + nexts[1];// keep 2 largest costif (cost >= maxCost) {maxCost2 = maxCost;maxCost = cost;} else if(cost >=maxCost2){maxCost2 = cost;}}// check if the 2 largest path is the global maxint curcost = maxCost + maxCost2;if (curcost > ans[0]) {ans[0] = curcost;}return maxCost;}
}

参考答案Go

package mainimport . "nc_tools"/** type Interval struct {*   Start int*   End int* }*//*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 树的直径* @param n int整型 树的节点个数* @param Tree_edge Interval类一维数组 树的边* @param Edge_value int整型一维数组 边的权值* @return int整型*/
func solve(n int, Tree_edge []*Interval, Edge_value []int) int {//核心就是树的最大直径(globalMax)一定是以某一个node为root最长的两个path-to-leaf.//就是普通dfs的同时算路径长度。////时间: O(n), DFS一次//空间: O(n)// node_id -> { {nei1, cost1}, {nei2, cost2}, ... }graph := map[int][]*Node{} //map表示图// construct graphfor i := 0; i < n; i++ {graph[i] = []*Node{}}for i := 0; i < n-1; i++ {// treat tree edge as bi-directionalfrom := Tree_edge[i].Startto := Tree_edge[i].Endgraph[from] = append(graph[from], &Node{to, Edge_value[i]})graph[to] = append(graph[to], &Node{from, Edge_value[i]})}// 因为edge是bi-directional, 随便从哪个node开始dfs都一样。这里用了node-0.// -1 作为parentans := []int{0}dfs(graph, &ans, 0, -1)return ans[0]
}func dfs(graph map[int][]*Node, ans *[]int, root, parent int) int {maxCost := 0maxCost2 := 0for _, nexts := range graph[root] {// NOTE: BaseCase (i.e. leaf) has only 1 nei, which is the parent//       thus leaf will return maxCost = 0 directly.if nexts.to == parent {continue}// recursively finds the max cost path to any leafcost := dfs(graph, ans, nexts.to, root) + nexts.cost// keep 2 largest costif cost >= maxCost {maxCost2 = maxCostmaxCost = cost} else if cost >= maxCost2 {maxCost2 = cost}}// check if the 2 largest path is the global maxcursot := maxCost + maxCost2if cursot > (*ans)[0] {(*ans)[0] = cursot}return maxCost
}type Node struct {to   intcost int
}

参考答案PHP

<?php/*class Interval{var $start = 0;var $end = 0;function __construct($a, $b){$this->start = $a;$this->end = $b;}
}*//*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** 树的直径* @param n int整型 树的节点个数* @param Tree_edge Interval类一维数组 树的边* @param Edge_value int整型一维数组 边的权值* @return int整型*/
function solve( $n ,  $Tree_edge ,  $Edge_value )
{//核心就是树的最大直径(globalMax)一定是以某一个node为root最长的两个path-to-leaf.//就是普通dfs的同时算路径长度。////时间: O(n), DFS一次//空间: O(n)// node_id -> { {nei1, cost1}, {nei2, cost2}, ... }$graph = [];for($i=0;$i<$n;$i++){$graph[$i] = [];}// construct graphfor($i=0;$i<$n-1;$i++){$from = $Tree_edge[$i]->start;$to = $Tree_edge[$i]->end;$graph[$from][count($graph[$from])] = [$to,$Edge_value[$i]];$graph[$to][count($graph[$to])] = [$from,$Edge_value[$i]];}$ans = [0];// 因为edge是bi-directional, 随便从哪个node开始dfs都一样。这里用了node-0.// -1 作为parentdfs($graph,$ans,0,-1);return $ans[0];
}// returns the max cost path-to-leaf from this root.
function dfs($graph,&$ans,$root,$parent){$max1 =0;$max2 = 0;foreach ($graph[$root] as $nexts) {// NOTE: BaseCase (i.e. leaf) has only 1 nei, which is the parent//       thus leaf will return maxCost = 0 directly.if($nexts[0] == $parent) continue; //不走回头路// recursively finds the max cost path to any leaf$cost = dfs($graph,$ans,$nexts[0],$root)+$nexts[1];// keep 2 largest costif($cost >= $max1){$max2=$max1;$max1 = $cost;}else if($cost >=$max2){$max2 = $cost;}}// check if the 2 largest path is the global max$curcost = $max1+$max2;if($curcost > $ans[0]){$ans[0] = $curcost;}return $max1;
}

http://www.ppmy.cn/embedded/21593.html

相关文章

web server apache tomcat11-21-monitor and management 监控与管理

前言 整理这个官方翻译的系列&#xff0c;原因是网上大部分的 tomcat 版本比较旧&#xff0c;此版本为 v11 最新的版本。 开源项目 从零手写实现 tomcat minicat 别称【嗅虎】心有猛虎&#xff0c;轻嗅蔷薇。 系列文章 web server apache tomcat11-01-官方文档入门介绍 web…

Django——Auth模块以及admin站点

Django——Auth模块 一、Auth 模块 Auth 用户认证&#xff0c;本质上也是设置 Session。 Django 认证系统同时处理认证和授权认证&#xff1a;验证一个用户是否为 django 声明的用户&#xff0c;如果是可以进行登录授权&#xff1a;决定一个已经验证的用户有哪些功能是允许操…

上位机开发PyQt5(一)【创建窗口、窗口标题、气泡、显示图片和图标、显示文字】

目录 一、 第一个Qt窗口 二、PyQt模块简介 三、窗口标题和气泡 setWindowTitle resize setToolTip 四、标签QLabel显示图片和图标 setPixmap setWindowIcon resize(label.pixmap().size()) 五、标签QLabel显示文字 setText QFont setPointSize setFont set…

SQL优化 第一章

此博客内容根据《SQL优化核心思想》的流程来进行书写&#xff0c;仅作为个人学习记录使用。当然&#xff0c;有问题可以一起来探讨&#xff01; 一、基数&#xff08;CARDINALITY&#xff09; 某个列唯一键&#xff08;Distinct_Keys&#xff09;的数量叫作基数。性别列只有男…

ZooKeeper的分布式锁

ZooKeeper的分布式锁机制主要利用ZooKeeper的节点特性&#xff0c;通过创建和删除节点来实现锁的控制。 实现步骤&#xff1a; 创建锁节点&#xff1a;当一个进程需要访问共享资源时&#xff0c;它会在ZooKeeper中创建一个唯一的临时顺序节点作为锁。尝试获取锁&#xff1a;进…

性能监控数据(本地、服务器)

CPU、内存、磁盘等的监控 一、mac本地性能监控 1. top 终端&#xff1a; top load Avg: 平均负载(1分钟&#xff0c;5 分钟&#xff0c;15 分钟)值不能超过 4&#xff0c;要不然就是超负荷运行 Tasks: 进程数 %Cpu(s): idle :剩余百分比 KiB Mem: free:剩余内存&#xff0…

.360勒索病毒分析,如何恢复被加密数据?

.360勒索病毒是什么&#xff1f; .360勒索病毒是一种恶意软件&#xff0c;它的主要特点和行为可以归纳为以下几点&#xff1a; 如果您的数据承载着企业机密、客户信赖与研发心血&#xff0c;欢迎添加技术服务号&#xff08;safe130&#xff09; 锁定与加密&#xff1a;.360勒索…

【Leetcode】33- 搜索旋转排序数组

题目简述 整数数组 nums 按升序排列&#xff0c;数组中的值互不相同。 在传递给函数之前&#xff0c;nums 在预先未知的某个下标 k&#xff08;0 < k < nums.length&#xff09;上进行了旋转&#xff0c;使数组变为 [nums[k], nums[k1], …, nums[n-1], nums[0], nums[1…