📌  相关文章
📜  细分树|设置2(范围最小查询)

📅  最后修改于: 2021-04-17 11:51:58             🧑  作者: Mango

在上一篇文章中,我们通过一个简单的例子介绍了段树。在本文中,将讨论范围最小查询问题,作为可以使用细分树的另一个示例。以下是问题陈述。

我们有一个数组arr [0。 。 。 n-1]。我们应该能够有效地找到从索引qs (查询开始)到qe (查询结束)的最小值,其中0 <= qs <= qe <= n-1

一个简单的解决方案是运行从qsqe的循环,并找到给定范围内的最小元素。在最坏的情况下,此解决方案需要O(n)时间。

另一种解决方案是创建2D数组,其中条目[i,j]将最小值存储在范围arr [i..j]中。现在可以以O(1)的时间计算给定范围的最小值,但是预处理需要O(n ^ 2)的时间。而且,此方法需要O(n ^ 2)额外的空间,这对于大型输入数组可能会变得很大。

段树可用于在适当的时间内进行预处理和查询。对于段树,预处理时间为O(n),范围最小查询到的时间为O(Logn)。存储段树所需的额外空间为O(n)。

段树的表示
1.叶节点是输入数组的元素。
2.每个内部节点代表其下所有叶子的最小值。

树的数组表示形式用于表示段树。对于索引i处的每个节点,左子节点在索引2 * i + 1处,右子节点在索引2 * i + 2处,父节点在索引处2 * i + 2处。 segmenttree2

从给定数组构造细分树
我们从一个段arr [0开始。 。 。 n-1]。每次我们将当前段分成两半(如果尚未将其变成长度为1的段),然后在这两个半段上调用相同的过程,则对于每个这样的段,我们将最小值存储在段树中节点。
除最后一个级别外,已构建的段树的所有级别都将被完全填充。而且,该树将是完整的二叉树,因为我们总是在每个级别将分段分为两半。由于构造的树始终是具有n个叶的完整二叉树,因此将有n-1个内部节点。因此,节点总数将为2 * n – 1。
段树的高度将为segmenttree3 。由于树是使用数组表示的,并且必须保持父索引和子索引之间的关系,因此分配给段树的内存大小将是段树

查询给定范围的最小值
构造树后,如何使用构造的段树进行范围最小查询。以下是获得最小值的算法。

// qs --> query start index, qe --> query end index
int RMQ(node, qs, qe) 
{
   if range of node is within qs and qe
        return value in node
   else if range of node is completely outside qs and qe
        return INFINITE
   else
    return min( RMQ(node's left child, qs, qe), RMQ(node's right child, qs, qe) )
}

执行:

C++
// C++ program for range minimum
// query using segment tree 
#include 
using namespace std;
  
// A utility function to get minimum of two numbers 
int minVal(int x, int y) { return (x < y)? x: y; } 
  
// A utility function to get the 
// middle index from corner indexes. 
int getMid(int s, int e) { return s + (e -s)/2; } 
  
/* A recursive function to get the
minimum value in a given range 
of array indexes. The following 
are parameters for this function. 
  
    st --> Pointer to segment tree 
    index --> Index of current node in the 
           segment tree. Initially 0 is 
           passed as root is always at index 0 
    ss & se --> Starting and ending indexes 
                of the segment represented 
                by current node, i.e., st[index] 
    qs & qe --> Starting and ending indexes of query range */
int RMQUtil(int *st, int ss, int se, int qs, int qe, int index) 
{ 
    // If segment of this node is a part 
    // of given range, then return 
    // the min of the segment 
    if (qs <= ss && qe >= se) 
        return st[index]; 
  
    // If segment of this node
    // is outside the given range 
    if (se < qs || ss > qe) 
        return INT_MAX; 
  
    // If a part of this segment
    // overlaps with the given range 
    int mid = getMid(ss, se); 
    return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1), 
                RMQUtil(st, mid+1, se, qs, qe, 2*index+2)); 
} 
  
// Return minimum of elements in range
// from index qs (query start) to 
// qe (query end). It mainly uses RMQUtil() 
int RMQ(int *st, int n, int qs, int qe) 
{ 
    // Check for erroneous input values 
    if (qs < 0 || qe > n-1 || qs > qe) 
    { 
        cout<<"Invalid Input"; 
        return -1; 
    } 
  
    return RMQUtil(st, 0, n-1, qs, qe, 0); 
} 
  
// A recursive function that constructs
// Segment Tree for array[ss..se]. 
// si is index of current node in segment tree st 
int constructSTUtil(int arr[], int ss, int se,
                                int *st, int si) 
{ 
    // If there is one element in array,
    // store it in current node of 
    // segment tree and return 
    if (ss == se) 
    { 
        st[si] = arr[ss]; 
        return arr[ss]; 
    } 
  
    // If there are more than one elements, 
    // then recur for left and right subtrees 
    // and store the minimum of two values in this node 
    int mid = getMid(ss, se); 
    st[si] = minVal(constructSTUtil(arr, ss, mid, st, si*2+1), 
                    constructSTUtil(arr, mid+1, se, st, si*2+2)); 
    return st[si]; 
} 
  
/* Function to construct segment tree 
from given array. This function allocates
memory for segment tree and calls constructSTUtil() to 
fill the allocated memory */
int *constructST(int arr[], int n) 
{ 
    // Allocate memory for segment tree 
  
    //Height of segment tree 
    int x = (int)(ceil(log2(n))); 
  
    // Maximum size of segment tree 
    int max_size = 2*(int)pow(2, x) - 1; 
  
    int *st = new int[max_size]; 
  
    // Fill the allocated memory st 
    constructSTUtil(arr, 0, n-1, st, 0); 
  
    // Return the constructed segment tree 
    return st; 
} 
  
// Driver program to test above functions 
int main() 
{ 
    int arr[] = {1, 3, 2, 7, 9, 11}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
  
    // Build segment tree from given array 
    int *st = constructST(arr, n); 
  
    int qs = 1; // Starting index of query range 
    int qe = 5; // Ending index of query range 
  
    // Print minimum value in arr[qs..qe] 
    cout<<"Minimum of values in range ["<C
// C program for range minimum query using segment tree
#include 
#include 
#include 
  
// A utility function to get minimum of two numbers
int minVal(int x, int y) { return (x < y)? x: y; }
  
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e) {  return s + (e -s)/2;  }
  
/*  A recursive function to get the minimum value in a given range
     of array indexes. The following are parameters for this function.
  
    st    --> Pointer to segment tree
    index --> Index of current node in the segment tree. Initially
              0 is passed as root is always at index 0
    ss & se  --> Starting and ending indexes of the segment represented
                  by current node, i.e., st[index]
    qs & qe  --> Starting and ending indexes of query range */
int RMQUtil(int *st, int ss, int se, int qs, int qe, int index)
{
    // If segment of this node is a part of given range, then return
    //  the min of the segment
    if (qs <= ss && qe >= se)
        return st[index];
  
    // If segment of this node is outside the given range
    if (se < qs || ss > qe)
        return INT_MAX;
  
    // If a part of this segment overlaps with the given range
    int mid = getMid(ss, se);
    return minVal(RMQUtil(st, ss, mid, qs, qe, 2*index+1),
                  RMQUtil(st, mid+1, se, qs, qe, 2*index+2));
}
  
// Return minimum of elements in range from index qs (query start) to
// qe (query end).  It mainly uses RMQUtil()
int RMQ(int *st, int n, int qs, int qe)
{
    // Check for erroneous input values
    if (qs < 0 || qe > n-1 || qs > qe)
    {
        printf("Invalid Input");
        return -1;
    }
  
    return RMQUtil(st, 0, n-1, qs, qe, 0);
}
  
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int *st, int si)
{
    // If there is one element in array, store it in current node of
    // segment tree and return
    if (ss == se)
    {
        st[si] = arr[ss];
        return arr[ss];
    }
  
    // If there are more than one elements, then recur for left and
    // right subtrees and store the minimum of two values in this node
    int mid = getMid(ss, se);
    st[si] =  minVal(constructSTUtil(arr, ss, mid, st, si*2+1),
                     constructSTUtil(arr, mid+1, se, st, si*2+2));
    return st[si];
}
  
/* Function to construct segment tree from given array. This function
   allocates memory for segment tree and calls constructSTUtil() to
   fill the allocated memory */
int *constructST(int arr[], int n)
{
    // Allocate memory for segment tree
  
    //Height of segment tree
    int x = (int)(ceil(log2(n))); 
  
    // Maximum size of segment tree
    int max_size = 2*(int)pow(2, x) - 1; 
  
    int *st = new int[max_size]; 
  
    // Fill the allocated memory st
    constructSTUtil(arr, 0, n-1, st, 0);
  
    // Return the constructed segment tree
    return st;
}
  
// Driver program to test above functions
int main()
{
    int arr[] = {1, 3, 2, 7, 9, 11};
    int n = sizeof(arr)/sizeof(arr[0]);
  
    // Build segment tree from given array
    int *st = constructST(arr, n);
  
    int qs = 1;  // Starting index of query range
    int qe = 5;  // Ending index of query range
  
    // Print minimum value in arr[qs..qe]
    printf("Minimum of values in range [%d, %d] is = %d\n",
                           qs, qe, RMQ(st, n, qs, qe));
  
    return 0;
}


Java
// Program for range minimum query using segment tree
class SegmentTreeRMQ
{
    int st[]; //array to store segment tree
  
    // A utility function to get minimum of two numbers
    int minVal(int x, int y) {
        return (x < y) ? x : y;
    }
  
    // A utility function to get the middle index from corner
    // indexes.
    int getMid(int s, int e) {
        return s + (e - s) / 2;
    }
  
    /*  A recursive function to get the minimum value in a given
        range of array indexes. The following are parameters for
        this function.
  
        st    --> Pointer to segment tree
        index --> Index of current node in the segment tree. Initially
                   0 is passed as root is always at index 0
        ss & se  --> Starting and ending indexes of the segment
                     represented by current node, i.e., st[index]
        qs & qe  --> Starting and ending indexes of query range */
    int RMQUtil(int ss, int se, int qs, int qe, int index)
    {
        // If segment of this node is a part of given range, then
        // return the min of the segment
        if (qs <= ss && qe >= se)
            return st[index];
  
        // If segment of this node is outside the given range
        if (se < qs || ss > qe)
            return Integer.MAX_VALUE;
  
        // If a part of this segment overlaps with the given range
        int mid = getMid(ss, se);
        return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
                RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
    }
  
    // Return minimum of elements in range from index qs (query
    // start) to qe (query end).  It mainly uses RMQUtil()
    int RMQ(int n, int qs, int qe)
    {
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe) {
            System.out.println("Invalid Input");
            return -1;
        }
  
        return RMQUtil(0, n - 1, qs, qe, 0);
    }
  
    // A recursive function that constructs Segment Tree for
    // array[ss..se]. si is index of current node in segment tree st
    int constructSTUtil(int arr[], int ss, int se, int si)
    {
        // If there is one element in array, store it in current
        //  node of segment tree and return
        if (ss == se) {
            st[si] = arr[ss];
            return arr[ss];
        }
  
        // If there are more than one elements, then recur for left and
        // right subtrees and store the minimum of two values in this node
        int mid = getMid(ss, se);
        st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
                constructSTUtil(arr, mid + 1, se, si * 2 + 2));
        return st[si];
    }
  
    /* Function to construct segment tree from given array. This function
       allocates memory for segment tree and calls constructSTUtil() to
       fill the allocated memory */
    void constructST(int arr[], int n)
    {
        // Allocate memory for segment tree
  
        //Height of segment tree
        int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
  
        //Maximum size of segment tree
        int max_size = 2 * (int) Math.pow(2, x) - 1;
        st = new int[max_size]; // allocate memory
  
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, 0);
    }
  
    // Driver program to test above functions
    public static void main(String args[]) 
    {
        int arr[] = {1, 3, 2, 7, 9, 11};
        int n = arr.length;
        SegmentTreeRMQ tree = new SegmentTreeRMQ();
  
        // Build segment tree from given array
        tree.constructST(arr, n);
  
        int qs = 1;  // Starting index of query range
        int qe = 5;  // Ending index of query range
  
        // Print minimum value in arr[qs..qe]
        System.out.println("Minimum of values in range [" + qs + ", "
                           + qe + "] is = " + tree.RMQ(n, qs, qe));
    }
}
// This code is contributed by Ankur Narain Verma


Python3
# Python3 program for range minimum 
# query using segment tree 
import sys;
from math import ceil,log2;
  
INT_MAX = sys.maxsize;
  
# A utility function to get 
# minimum of two numbers 
def minVal(x, y) :
    return x if (x < y) else y; 
  
# A utility function to get the 
# middle index from corner indexes. 
def getMid(s, e) :
    return s + (e - s) // 2; 
  
""" A recursive function to get the 
minimum value in a given range 
of array indexes. The following 
are parameters for this function. 
  
    st --> Pointer to segment tree 
    index --> Index of current node in the 
        segment tree. Initially 0 is 
        passed as root is always at index 0 
    ss & se --> Starting and ending indexes 
                of the segment represented 
                by current node, i.e., st[index] 
    qs & qe --> Starting and ending indexes of query range """
def RMQUtil( st, ss, se, qs, qe, index) :
  
    # If segment of this node is a part 
    # of given range, then return 
    # the min of the segment 
    if (qs <= ss and qe >= se) :
        return st[index]; 
  
    # If segment of this node 
    # is outside the given range 
    if (se < qs or ss > qe) :
        return INT_MAX; 
  
    # If a part of this segment 
    # overlaps with the given range 
    mid = getMid(ss, se); 
    return minVal(RMQUtil(st, ss, mid, qs, 
                          qe, 2 * index + 1), 
                  RMQUtil(st, mid + 1, se,
                          qs, qe, 2 * index + 2)); 
  
# Return minimum of elements in range 
# from index qs (query start) to 
# qe (query end). It mainly uses RMQUtil() 
def RMQ( st, n, qs, qe) : 
  
    # Check for erroneous input values 
    if (qs < 0 or qe > n - 1 or qs > qe) :
      
        print("Invalid Input"); 
        return -1; 
      
    return RMQUtil(st, 0, n - 1, qs, qe, 0); 
  
# A recursive function that constructs 
# Segment Tree for array[ss..se]. 
# si is index of current node in segment tree st 
def constructSTUtil(arr, ss, se, st, si) :
  
    # If there is one element in array, 
    # store it in current node of 
    # segment tree and return 
    if (ss == se) :
  
        st[si] = arr[ss]; 
        return arr[ss]; 
  
    # If there are more than one elements, 
    # then recur for left and right subtrees 
    # and store the minimum of two values in this node 
    mid = getMid(ss, se); 
    st[si] = minVal(constructSTUtil(arr, ss, mid,
                                    st, si * 2 + 1),
                    constructSTUtil(arr, mid + 1, se,
                                    st, si * 2 + 2)); 
      
    return st[si]; 
  
"""Function to construct segment tree 
from given array. This function allocates 
memory for segment tree and calls constructSTUtil()
to fill the allocated memory """
def constructST( arr, n) :
  
    # Allocate memory for segment tree 
  
    # Height of segment tree 
    x = (int)(ceil(log2(n))); 
  
    # Maximum size of segment tree 
    max_size = 2 * (int)(2**x) - 1; 
   
    st = [0] * (max_size); 
  
    # Fill the allocated memory st 
    constructSTUtil(arr, 0, n - 1, st, 0); 
  
    # Return the constructed segment tree 
    return st; 
  
# Driver Code
if __name__ == "__main__" : 
  
    arr = [1, 3, 2, 7, 9, 11]; 
    n = len(arr); 
  
    # Build segment tree from given array 
    st = constructST(arr, n); 
  
    qs = 1; # Starting index of query range 
    qe = 5; # Ending index of query range 
  
    # Print minimum value in arr[qs..qe] 
    print("Minimum of values in range [", qs, 
          ",", qe, "]", "is =", RMQ(st, n, qs, qe)); 
  
# This code is contributed by AnkitRai01


C#
// C# Program for range minimum 
// query using segment tree
using System;
      
public class SegmentTreeRMQ
{
    int []st; //array to store segment tree
  
    // A utility function to 
    // get minimum of two numbers
    int minVal(int x, int y) 
    {
        return (x < y) ? x : y;
    }
  
    // A utility function to get the
    //  middle index from corner indexes.
    int getMid(int s, int e) 
    {
        return s + (e - s) / 2;
    }
  
    /* A recursive function to get
        the minimum value in a given
        range of array indexes. 
        The following are parameters for
        this function.
  
        st --> Pointer to segment tree
        index --> Index of current node in the 
        segment tree. Initially 0 is passed 
        as root is always at index 0
        ss & se --> Starting and ending indexes of the segment
                    represented by current node, i.e., st[index]
        qs & qe --> Starting and ending indexes of query range */
    int RMQUtil(int ss, int se, int qs, int qe, int index)
    {
        // If segment of this node is a 
        // part of given range, then
        // return the min of the segment
        if (qs <= ss && qe >= se)
            return st[index];
  
        // If segment of this node
        // is outside the given range
        if (se < qs || ss > qe)
            return int.MaxValue;
  
        // If a part of this segment 
        // overlaps with the given range
        int mid = getMid(ss, se);
        return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
                RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
    }
  
    // Return minimum of elements 
    // in range from index qs (query
    // start) to qe (query end).
    // It mainly uses RMQUtil()
    int RMQ(int n, int qs, int qe)
    {
        // Check for erroneous input values
        if (qs < 0 || qe > n - 1 || qs > qe) 
        {
            Console.WriteLine("Invalid Input");
            return -1;
        }
  
        return RMQUtil(0, n - 1, qs, qe, 0);
    }
  
    // A recursive function that 
    // constructs Segment Tree for
    // array[ss..se]. si is index 
    // of current node in segment tree st
    int constructSTUtil(int []arr, int ss, int se, int si)
    {
        // If there is one element in array, 
        // store it in current node of 
        // segment tree and return
        if (ss == se) 
        {
            st[si] = arr[ss];
            return arr[ss];
        }
  
        // If there are more than one elements,
        // then recur for left and right subtrees
        // and store the minimum of two values in this node
        int mid = getMid(ss, se);
        st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
                constructSTUtil(arr, mid + 1, se, si * 2 + 2));
        return st[si];
    }
  
    /* Function to construct segment 
    tree from given array. This function
    allocates memory for segment tree 
    and calls constructSTUtil() to
    fill the allocated memory */
    void constructST(int []arr, int n)
    {
        // Allocate memory for segment tree
  
        // Height of segment tree
        int x = (int) (Math.Ceiling(Math.Log(n) / Math.Log(2)));
  
        // Maximum size of segment tree
        int max_size = 2 * (int) Math.Pow(2, x) - 1;
        st = new int[max_size]; // allocate memory
  
        // Fill the allocated memory st
        constructSTUtil(arr, 0, n - 1, 0);
    }
  
    // Driver code
    public static void Main() 
    {
        int []arr = {1, 3, 2, 7, 9, 11};
        int n = arr.Length;
        SegmentTreeRMQ tree = new SegmentTreeRMQ();
  
        // Build segment tree from given array
        tree.constructST(arr, n);
  
        int qs = 1; // Starting index of query range
        int qe = 5; // Ending index of query range
  
        // Print minimum value in arr[qs..qe]
        Console.WriteLine("Minimum of values in range [" + qs + ", "
                        + qe + "] is = " + tree.RMQ(n, qs, qe));
    }
}
  
/* This code contributed by PrinciRaj1992 */


输出:

Minimum of values in range [1, 5] is = 2

时间复杂度:
树构建的时间复杂度为O(n)。总共有2n-1个节点,并且在树结构中每个节点的值仅计算一次。

查询的时间复杂度为O(Logn)。为了查询最小范围,我们在每个级别最多处理两个节点,并且级别数为O(Logn)。

请参考以下链接以获取更多解决方案,以解决范围最小的查询问题。
https://www.geeksforgeeks.org/range-minimum-query-for-static-array/
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#Range_Minimum_Query_(RMQ)
http://wcipeg.com/wiki/Range_minimum_query