Range minimum & Lowest common ancestors

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BigFatSheep/article/details/80679809

If we can solve one of these two problems in space S(n) and query time Q(n), then the same is true for the other problem.

We can solve the two problems with O(n log n) space and O(1) query time (fairly easy)

We can solve the two problems with O(n) space and O(1) query time (more complicated)

Range Minimum

给一个静态数组A,找到i到j范围内的最小值或它的index,并且在有多个最小值的情况下依然能正确判断。

一些可行方案:

  1. Just store the array A without preprocessing. Compute query(i,j) each time.正常储存查找
    • O(n) space for array A (O(1) extra space, so in-place)
    • O(n) query time
  2. Build table T[i, j] storing query(i,j)将每一个范围的值存放在一个二位数组中。
    • O(n^2) space
    • O(1) query time
  3. Range query solution from last time: Binary tree, elements of A are leaves, each internal node stores minimum of its two children query(i,j) is double binary search每次都进行range query。
    • O(n) space
    • O(log n) query time

O(n log n) space, O(1) query time

如果两个区间重合,可以通过搜索两个区间的最小值再比较来代大的区间的最小值。
- Store a subset of the precomputed T(i, j)
- Make the subset big enough that every possible range is the union of two overlapping ranges for which we have precomputed the result
存在U[i,k]中,用k表示区间长度,k最大到 l o g 2 n , 用i表示开始位置,往后k个位置的最小值。

查询时,很直接
k = l o g 2 ( j i + 1 )
计算区间长度,不够再加
return min ( U [ I , k ] , U [ j 2 k + 1 , k )

Query time is O(1)
construct time O(n log n) time, O(n log n) space

Lowest Common Ancestors

Two applications of Lowest Common Ancestor (LCA) problem
1. Distances in trees
2. Bandwidth queries in tree network
The second application leads us into
I Cartesian trees
I Connection between Range Minimum and LCA.

Calculating Distances in trees

distance(x,y) = depth(x) + depth(y) − 2 · depth(LCA(x, y))

Bandwidth in Tree Networks

给一棵为确定根的树N代表一个网络,每条边有bandwith
Given two network nodes x and y, bandwidth(x,y) is the minimum bandwidth on the path between x and y.
如何快速找到最小bandwidth?使用Cartesian Tree

Cartesian Tree

笛卡尔树

一个序列的笛卡尔树有这样的性质:
- 笛卡尔树的中序遍历产生序列
- 树是堆排序的
一个例子就是树堆

笛卡尔树的叶子节点是网络的节点
根结点是最小权重的边。
内部节点是网络的边。
随意那边是左孩子,哪边是右孩子。

为了找到x and y的minimum bandwidth,
1. 找到cartesian tree的叶子
2. 找到他们的公共祖先。

构建笛卡尔树,不断拿出网络中的最小权重的边,分成左右两棵子树,递归操作。

Using LCA to solve Range Minimum

将range minimum使用Cartesian tree转化为LCA问题。
1.存储点对(value,position)
2.根为最小值,字典顺序,左边优先
3.递归左右子树
4.此时的RangeMinx(x,y)变为找x,y的最小公共祖先。

构建
查找

Using Range Minimum to solve LCA

给一棵树,
1. 给每一条边分配到root的距离
2. 前序遍历树,注意回溯的情况也要存,将点对存储在数组中
3. LCA(x, y) 即为RangeMin(firstindex(x),firstindex(y))

猜你喜欢

转载自blog.csdn.net/BigFatSheep/article/details/80679809