首页 > 分享 > 树的直径算法解析

树的直径算法解析

树的直径

最新推荐文章于 2024-12-31 10:52:29 发布

没在尽心,怎么可能 于 2021-01-18 11:29:58 发布

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

题目描述

代码分析:

import java.util.*;

class Interval {

int start;

int end;

}

public class 树的直径 {

int res=0;

public int solve (int n, Interval[] Tree_edge, int[] Edge_value) {

ArrayList<int[]>[] map = new ArrayList[n];

for(int i = 0; i < n; i++) map[i] = new ArrayList();

for(int i = 0; i < Tree_edge.length; i++) {

map[Tree_edge[i].start].add(new int[] { Tree_edge[i].end, Edge_value[i] } );

map[Tree_edge[i].end].add(new int[] { Tree_edge[i].start, Edge_value[i] } );

}

dfs(map, 0, new boolean[n]);

return res;

}

private int dfs(ArrayList<int[]>[] map, int index, boolean[] visited) {

visited[index] = true;

ArrayList<int[]> list = map[index];

int weight1 = 0, weight2 = 0;

for(int[] child2weight: list) {

int child = child2weight[0];

int weight = child2weight[1];

if(visited[child]) continue;

int num = weight + dfs(map, child, visited);

if(num > weight1) {

weight2 = weight1;

weight1 = num;

} else if(num > weight2) {

weight2 = num;

}

if(weight1 + weight2 > res) res = weight1 + weight2;

}

return Math.max(weight1, weight2);

}

}

相关知识

算法复杂度解析与实例
Matlab人脸检测算法详解
算法设计题解析
树干解析
聚类算法和分类算法总结
利用带花树算法解决一般图的最大匹配
机器学习算法
【机器学习】基于KNN算法实现鸢尾花数据集的分类
春树全面解析——了解这种树木的一切(春树是什么树)
js植物算法

网址: 树的直径算法解析 https://m.huajiangbk.com/newsview1407799.html

所属分类:花卉
上一篇: DD
下一篇: 出木材最多的树,鸡毛松树干直径达