算法 - 树中所有节点的最大距离

4
那么,在树中找到两个节点之间的最长路径相当容易。但是我想要的是,找到从节点 x 到树中另一个节点的最长路径,对于所有的 x
这个问题也可以表述为:计算可以从给定树构建的所有有根树的高度。
一种方法,当然,是对树中的所有节点执行 BFS/DFS,并记住找到的最远节点。然而,这会导致 O(N2) 的时间复杂度。是否可能做得更好呢?
编辑:仅仅是为了概括,我的问题不是如何在图中找到最长路径。如果可能的话,它是如何在比 O(N2) 更好的时间复杂度下找到包含给定节点 x 的最长路径,对于所有节点 x

2
@Guido 不,那是一个相关但不同的问题。 - David Eisenstat
是的,我想找到N条路径,每个节点都有一条。它们的表示方式并不重要。我只对每个特定节点的每条路径的长度感兴趣(也就是说,如果以该节点为根,则树的高度)。我只是想知道是否有比O(N^2)更好的算法。 - Nu Nunu
每个节点到所有其他节点的最长路径只能在O(n^2)中得到最佳结果,除非您指定某些条件,例如树的一部分等。 - Mike
这个问题是关于从每个节点x开始的路径还是包含每个节点x的路径?你两种说法都有。暂时给-1分。 - j_random_hacker
我在我的答案中添加了一些代码。这是一个不错的小问题。 - Gene
显示剩余2条评论
3个回答

1
是的,有一个O(n)算法。 将树视为未根据的图形-每个节点具有双向边,不形成循环。 对于具有相邻节点a_i的给定节点p,我们将计算高度Hpa_i。 Hpa_i的高度是子树的高度以根p为根(即在此部分算法中,我们暂时考虑将节点a_i视为p的父节点而获得的)。 如果您对每个节点到叶子节点的最长路径感兴趣(您的问题及其标题让人怀疑您实际上要计算什么),则只需max{ Hpa_i for all i }。 相应的i值给出了最长的路径本身。 另一方面,如果您对通过p的最长路径感兴趣,那么它将是从{ len(p--a_i) + Ha_ip for all i }选择的最大对的总和,并且两个相应的i值给出了最长的路径本身。 因此,如果我们拥有每个节点的高度,则获取最终结果就是简单的O(n)工作。

现在需要计算所有节点的高度。为此,从一个特殊的深度优先搜索开始。它接受两个节点作为参数。第一个节点p是正在搜索的节点,第二个节点q ∈ {a_i} 是当前被认为是p的父节点的相邻节点。让U成为将节点对映射到高度的映射:(p, q) -> Hpq

function search_and_label(p, q)
  if ((p, q) maps to height Hpq in U ) { return Hpq }
  if (p == null) { add (p, q) -> 0 to U and return 0 }
  let h = max(all x adjacent to p, not equal to q) {
            len(p--x) + search_and_label(x, p)
          }
  add (p, q) -> h to U
  return h
  

现在我们可以找到所有的高度。
 Add mappings (p, x)->null to U for all nodes p and adjacent nodes x
 Also add a mapping (p, z)->null to U for all nodes p having < 3 adjacent
 while (U contains a mapping of the form (p, x)->null) 
   search_and_label(p, x) // this replaces the null mapping with a height

这将是一个O(n)的计算,因为它在每条边上都花费了恒定的工作量,而树中边的数量为n-1。 代码 今天下雨了,所以这里有一些代码,可以在O(n)的时间内生成一个随机树并用最长路径信息标记它。首先是典型的输出。每个节点都带有自己的编号,然后是包含它的最长路径的长度,接着是该路径上相邻节点的编号。小的边缘标签是高度信息。首先是相反子树的高度,然后是该子树中最长叶节点路径所在的节点:

Decorated Tree

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * An undirected graph. It has a builder that fills the graph with a random
 * unrooted tree. And it knows how to decorate itself with longest path
 * information when it's such a tree.
 */
class Graph {

  /**
   * Edge p--q is represented as edges[p][q]=dq and edges[q][p]=dp, where dq and
   * dp are node data. They describe the respective end of the edge:
   * <ul>
   * <li>dq.len == dp.len, the edge length
   * <li>dq.h is the height of subtree rooted at p with q as parent.
   * <li>dq.next is the child of p (with respect to parent q) rooting the max
   * height subtree.
   * </ul>
   */
  final Map<Node, Map<Node, EdgeData>> edges = new HashMap<>();

  /**
   * A node in the graph.
   */
  static class Node {

    final int id; // Unique node id.
    Node a, b;    // Adjacent nodes on longest path.
    double len;   // Length of longest path.

    Node(int i) {
      this.id = i;
    }
  }

  /**
   * Data associated with one end of an edge in the graph.
   */
  static class EdgeData {

    final double len;  // Edge length.
    Double h;          // Subtree height.
    Node next;         // Next node on max length path to leaf.

    EdgeData(double len) {
      this.len = len;
    }
  }

  /**
   * Add a new node to the graph and return it.
   */
  Node addNode() {
    Node node = new Node(currentNodeIndex++);
    edges.put(node, new HashMap<>());
    return node;
  }
  private int currentNodeIndex = 0;

  /**
   * Add an undirected edge between nodes x and y.
   */
  void addEdge(Node x, Node y, double len) {
    edges.get(x).put(y, new EdgeData(len));
    edges.get(y).put(x, new EdgeData(len));
  }

  /**
   * Decorate subtree rooted at p assuming adjacent node q is its parent.
   * Decorations are memos. No subtree is decorated twice.
   */
  EdgeData decorateSubtree(Node p, Node q) {
    Map<Node, EdgeData> adjacent = edges.get(p);
    EdgeData data = adjacent.get(q);
    if (data.h == null) {
      data.h = 0.0;
      for (Map.Entry<Node, EdgeData> x : adjacent.entrySet()) {
        if (x.getKey() != q) {
          double hNew = x.getValue().len + decorateSubtree(x.getKey(), p).h;
          if (hNew > data.h) {
            data.h = hNew;
            data.next = x.getKey();
          }
        }
      }
    }
    return data;
  }

  /**
   * Decorate node p with longest path information. Decorations are memos. No
   * node nor its associated subtrees are decorated twice.
   */
  Node decorateNode(Node p) {
    if (p.a == null) {
      double ha = 0.0, hb = 0.0;
      for (Map.Entry<Node, EdgeData> x : edges.get(p).entrySet()) {
        double hNew = x.getValue().len + decorateSubtree(x.getKey(), p).h;
        // Track the largest two heights and corresponding subtrees.
        if (hNew > ha) {
          p.b = p.a;
          hb = ha;
          p.a = x.getKey();
          ha = hNew;
        } else if (hNew > hb) {
          p.b = x.getKey();
          hb = hNew;
        }
      }
      p.len = ha + hb;
    }
    return p;
  }

  /**
   * Decorate the entire tree. This isn't necessary if the lazy decorators are
   * used as accessors.
   */
  void decorateAll() {
    for (Node p : edges.keySet()) {
      decorateNode(p);
    }
  }

  /**
   * Random tree builder. Parameters are a maximum edge length, tree radius in
   * number of edges, and partitions p[k] giving probabilities of branching with
   * degree k.
   */
  class RandomTreeBuilder {

    final Random gen = new Random();
    final long seed;
    final float[] partitions;
    final int maxLen;
    final int radius;

    RandomTreeBuilder(long seed, float[] partitions, int maxLen, int radius) {
      this.seed = seed;
      this.partitions = partitions;
      this.maxLen = maxLen;
      this.radius = radius;
    }

    private void growTree(Node p, int radius) {
      if (radius > 0) {
        float random = gen.nextFloat();
        float pSum = 0f;
        for (float partition : partitions) {
          pSum += partition;
          if (random < pSum) {
            return;
          }
          Node q = addNode();
          addEdge(p, q, 1 + gen.nextInt(maxLen));
          growTree(q, radius - 1);
        }
      }
    }

    /**
     * Build a tree in the graph. Any existing nodes and edges are erased.
     */
    void build() {
      if (seed != 0) {
        gen.setSeed(seed);
      }
      edges.clear();
      Node p = addNode();
      Node q = addNode();
      addEdge(p, q, 1 + gen.nextInt(maxLen));
      growTree(p, radius);
      growTree(q, radius);
    }
  }

  class TreePrinter {

    PrintStream stream;

    TreePrinter(PrintStream stream) {
      this.stream = stream;
    }

    /**
     * Print graph in the GraphViz DOT language.
     */
    void print() {
      stream.println("graph tree {");
      stream.println(" graph [layout = twopi overlap=false ranksep=1.7]");
      Node p = edges.keySet().iterator().next();
      Node q = edges.get(p).keySet().iterator().next();
      printEdge(p, q);
      print(p, q);
      print(q, p);
      for (Node x : edges.keySet()) {
        printNode(decorateNode(x));
      }
      stream.println("}");
    }

    /**
     * Print edge {@code p--q} in the GraphViz DOT language.
     */
    private void printEdge(Node p, Node q) {
      EdgeData dq = decorateSubtree(p, q);
      EdgeData dp = decorateSubtree(q, p);
      stream.format(" n%d--n%d [label=\"%.0f\" fontsize=8 "
          + "headlabel=\"%.0f:%s\" taillabel=\"%.0f:%s\"]\n",
          p.id, q.id, dq.len,
          dp.h, dp.next == null ? "-" : dp.next.id,
          dq.h, dq.next == null ? "-" : dq.next.id);
    }

    /**
     * Print node p in the GraphViz DOT language.
     */
    private void printNode(Node p) {
      stream.format(" n%d [ label=\"%d (%.0f:%s-%s)\" fontsize=10 ]\n",
          p.id, p.id, p.len,
          p.a == null ? "-" : p.a.id, p.b == null ? "-" : p.b.id);
    }

    /**
     * Print the sub-tree rooted at node p, treating node q as its parent.
     */
    private void print(Node p, Node q) {
      for (Node x : edges.get(p).keySet()) {
        if (x != q) {
          printEdge(p, x);
          print(x, p);
        }
      }
    }
  }

  public static void main(String[] args) throws FileNotFoundException {
    PrintStream stream = args.length > 0
        ? new PrintStream(new File(args[0]))
        : System.out;
    Graph graph = new Graph();
    graph.new RandomTreeBuilder(42L, new float[]{0.3f, 0.1f, 0.3f, 0.2f}, 10, 5)
        .build();
    graph.new TreePrinter(stream).print();
  }
}

1
len(p--a)是边(p, a)的长度吗?如果是,那么我认为“从{len(p--a)+Hap,len(p--b)+Hbp,len(p--c)+Hcp}中选择最大的一对”不是你要找的,因为例如第一个术语“len(p--a)+Hap”似乎描述了一个(而不是路径),该树由经过顶点b、p和c的长度为Hap的路径以及边缘(p, a)组成(使得顶点p的度数为3)。 - j_random_hacker
1
@j_random_hacker Hap 是以 a 为根的子树的高度(即从 a 到叶子节点的最长路径,不使用边 a--p)。加上 len(p--a) 可以得到从 p 开始到叶子节点的总最大距离,并使用边 (p--a)。如果有时间,我会写代码。 - Gene
谢谢!我现在明白我把Hpa和Hap搞混了。我认为你的解决方案能够解决包含每个顶点x的最长路径问题,也可以通过简单选择该集合中三个项目中的最大值(而不是最大两个的总和)来解决从每个顶点x开始的最长路径问题(OP没有明确说明想要哪一个)。 :) - j_random_hacker
还有一点需要注意:我花了一些时间才明白这行代码 if ((p, x) maps to height Hpx in U ) 只是在检查是否已经计算并存储了(p, x)的高度值在备忘录表中,而不是将查找结果与Hpx的某个计算值进行比较。你可能需要稍微明确一下这一点。 - j_random_hacker
@j_random_hacker 是的,我一定会在有时间的时候进行优化。 - Gene
显示剩余3条评论

0
这是我的解决方案。 第一遍 递归地遍历所有节点,并为树中的每个节点设置M(最大深度)。
M(X) = 0 IF X DOES NOT EXIST
EXIST(X) = 1 IF X EXISTS, 0 OTHERWISE

M = MAX(EXIST(LEFT) + M(LEFT), EXIST(RIGHT) + M(RIGHT))

第二遍 递归地遍历所有节点,并设置 R(通过树中任何根的最大距离),通过取子节点的最大2个值的总和,然后加上如果存在于任一子节点上的路径的距离。

IF SUM(EXIST(..)) = 0 THEN R = 0
IF SUM(EXIST(..)) = 1 THEN R = X.M + 1 WHERE EXIST(X) = 1

R = SUM(MAX2(x,y: x.M >= y.M >= ..)) + EXIST(x) + EXIST(y)

R: the node max distance through.
M: the node max depth.

最终遍历递归地遍历所有节点,并在树中找到R的最大值。

R(NULL) = 0
R(THIS) = R OF THE CURRENT NODE

S = MAX(R(THIS), S(CHILD1), .. S(CHILDX))

复杂度

TIME = N + N + N = 3N

TIME ~ O(N)

1
您似乎正在尝试计算树中的整体最长路径,而OP明确表示他/她并没有要求。为了使其适应于查找从每个节点x开始的最长路径(或包含每个节点x的最长路径;OP在这里不太清楚),我认为您还需要考虑通过父节点向上返回的路径。 - j_random_hacker
@j_random_hacker,你是对的,我读错了。这会更加困难,我需要更多时间来重新考虑并尝试在节点之间找到共同点,以便我可以将其适配为O(n)。我已经通过执行“+ EXIST(x)”来记录与父链接。 - Khaled.K

0
你的问题可以简化为寻找一棵树上最长的路径。这也被称为树的直径。
这是一个深入研究的主题,有很多资源提供了一个时间复杂度为O(n)的算法,其中n是图中节点的数量。
请参见thisthis

1
请问您能否解释一下它如何缩短树中的最长路径?我已经知道如何找到树的直径,但这不是我想问的。我的问题是这样开始的:“因此...在树中找到两个节点之间的最长路径相当容易。但我想要的是....” - Nu Nunu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接