博客
关于我
【Lintcode】291. Second Diameter
阅读量:188 次
发布时间:2019-02-28

本文共 2355 字,大约阅读时间需要 7 分钟。

一棵树型无向带权图的次大直径是指所有两点间距离中的第二长,包括相同长度的路径。为了求解次大直径,我们可以参考以下步骤:

1. 求直径的两个端点

首先,使用广度优先搜索(BFS)从任意节点出发,找到最远的节点u。接着,再次从u出发,进行BFS找到最远的节点v。这样,u和v就是直径的两个端点。

2. 计算次大直径

从u出发,排除v,进行BFS,找到最远的节点a。同样地,从v出发,排除u,进行BFS,找到最远的节点b。次大直径即为a到u的距离与b到v的距离中的较大者。

3. 算法正确性

根据树的性质,任何最长路径都必然连接直径的两个端点。因此,从任意节点出发的最远点必定是直径的一个端点。

4. 代码实现

import java.util.*;public class Solution {    private long res;    public long getSecondDiameter(int[][] edge) {        int n = edge.length + 1;        Map
> graph = buildGraph(edge); int far1 = bfs(0, graph, -1, new boolean[n]); int far2 = bfs(far1, graph, -1, new boolean[n]); bfs(far1, graph, far2, new boolean[n]); bfs(far2, graph, far1, new boolean[n]); return res; } private int bfs(int v, Map
> graph, int u, boolean[] visited) { Queue
queue = new LinkedList<>(); queue.offer(new long[]{v, 0}); visited[v] = true; int farV = v; long farDis = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { long[] cur = queue.poll(); int nextV = (int) cur[0]; if (graph.containsKey(nextV)) { for (int[] next : graph.get(nextV)) { if (next[0] != u && !visited[next[0]]) { if (next[1] + cur[1] > farDis) { farDis = next[1] + cur[1]; farV = next[0]; } visited[next[0]] = true; queue.offer(new long[]{next[0], next[1] + cur[1]}); } } } } } if (u != -1) { res = Math.max(res, farDis); } return farV; } private Map
> buildGraph(int[][] edges) { Map
> graph = new HashMap<>(); for (int[] edge : edges) { graph.putIfAbsent(edge[0], new ArrayList<>()); graph.get(edge[0]).add(new int[]{edge[1], edge[2]}); graph.putIfAbsent(edge[1], new ArrayList<>()); graph.get(edge[1]).add(new int[]{edge[0], edge[2]}); } return graph; }}

5. 时空复杂度

  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

该算法通过两次BFS找到直径,再从直径端点出发计算次大直径,确保了在树结构下的高效计算。

转载地址:http://adjs.baihongyu.com/

你可能感兴趣的文章
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
Nitrux 3.8 发布!性能全面提升,带来非凡体验
查看>>
NI笔试——大数加法
查看>>
NLog 自定义字段 写入 oracle
查看>>
NLog类库使用探索——详解配置
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP 项目:维基百科文章爬虫和分类【01】 - 语料库阅读器
查看>>
NLP_什么是统计语言模型_条件概率的链式法则_n元统计语言模型_马尔科夫链_数据稀疏(出现了词库中没有的词)_统计语言模型的平滑策略---人工智能工作笔记0035
查看>>
NLP学习笔记:使用 Python 进行NLTK
查看>>
NLP的神经网络训练的新模式
查看>>
NLP问答系统:使用 Deepset SQUAD 和 SQuAD v2 度量评估
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>