📌  相关文章
📜  查询具有给定范围内的值的数组元素的计数并进行更新

📅  最后修改于: 2021-05-25 03:48:04             🧑  作者: Mango

给定大小为N的数组arr []和由以下两种类型的查询组成的矩阵Q

  • 1 LR:打印位于[L,R]范围内的元素数量。
  • 2 ix:设置arr [i] = x

例子:

天真的方法:
解决此问题的最简单方法如下:

  • 对于类型(1 LR)的查询,遍历整个数组并计算数组中元素的数量,以使L≤arr [i]≤R 。最后,打印计数。
  • 对于类型(2 ix)的查询,将arr [i]替换为x

下面是上述方法的实现:

C++
// C++ code for queries for number
// of elements that lie in range
// [l, r] (with updates)
#include 
using namespace std;
 
// Function to set arr[index] = x
void setElement(int* arr, int n,
                int index, int x)
{
    arr[index] = x;
}
 
// Function to get count of elements
// that lie in range [l, r]
int getCount(int* arr, int n,
            int l, int r)
{
    int count = 0;
 
    // Traverse array
    for (int i = 0; i < n; i++) {
 
        // If element lies in the
        // range [L, R]
        if (arr[i] >= l
            && arr[i] <= r) {
 
            // Increase count
            count++;
        }
    }
    return count;
}
 
// Function to solve each query
void SolveQuery(int arr[], int n,
                vector > >
                    Q)
{
    int x;
 
    for (int i = 0; i < Q.size(); i++) {
        if (Q[i].first == 1) {
            x = getCount(arr, n,
                        Q[i].second.first,
                        Q[i].second.second);
 
            cout << x << " ";
        }
        else {
            setElement(arr, n,
                    Q[i].second.first,
                    Q[i].second.second);
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 2, 3, 4, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    vector > > Q
        = { { 1, { 3, 5 } },
            { 1, { 2, 4 } },
            { 1, { 1, 2 } },
            { 2, { 1, 7 } },
            { 1, { 1, 2 } } };
    SolveQuery(arr, n, Q);
 
    return 0;
}


Java
// Java code for queries for number
// of elements that lie in range
// [l, r] (with updates)
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to set arr[index] = x
static void setElement(int[] arr, int n,
                       int index, int x)
{
    arr[index] = x;
}
 
// Function to get count of elements
// that lie in range [l, r]
static int getCount(int[] arr, int n,
                    int l, int r)
{
    int count = 0;
     
    // Traverse array
    for(int i = 0; i < n; i++)
    {
         
        // If element lies in the
        // range [L, R]
        if (arr[i] >= l && arr[i] <= r)
        {
            // Increase count
            count++;
        }
    }
    return count;
}
 
// Function to solve each query
static void SolveQuery(int arr[], int n,
                       ArrayList> Q)
{
    int x;
  
    for(int i = 0; i < Q.size(); i++)
    {
        if (Q.get(i).get(0) == 1)
        {
            x = getCount(arr, n,
                         Q.get(i).get(1),
                         Q.get(i).get(2));
  
            System.out.print(x + " ");
        }
        else
        {
            setElement(arr, n,
                       Q.get(i).get(1),
                       Q.get(i).get(2));
        }
    }
}
  
// Driver code
public static void main (String[] args)
{
    int arr[] = { 1, 2, 2, 3, 4, 4, 5, 6 };
    int n = arr.length;
     
    ArrayList> Q = new ArrayList<>();
    Q.add(Arrays.asList(1, 3, 5));
    Q.add(Arrays.asList(1, 2, 4)); 
    Q.add(Arrays.asList(1, 1, 2));
    Q.add(Arrays.asList(2, 1, 7));
    Q.add(Arrays.asList(1, 1, 2));
     
    SolveQuery(arr, n, Q);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 code for queries for number
# of elements that lie in range
# [l, r] (with updates)
from typing import Generic, List, TypeVar
 
T = TypeVar('T')
V = TypeVar('V')
 
class Pair(Generic[V, T]):
     
    def __init__(self, first: V, second: T) -> None:
         
        self.first = first
        self.second = second
 
# Function to set arr[index] = x
def setElement(arr: List[int], n: int,
                   index: int, x: int) -> None:
                        
    arr[index] = x
 
# Function to get count of elements
# that lie in range [l, r]
def getCount(arr: List[int], n: int,
                     l: int, r: int) -> int:
 
    count = 0
 
    # Traverse array
    for i in range(n):
 
        # If element lies in the
        # range [L, R]
        if (arr[i] >= l and arr[i] <= r):
 
            # Increase count
            count += 1
 
    return count
 
# Function to solve each query
def SolveQuery(arr: List[int], n: int,
            Q: List[Pair[int, Pair[int, int]]]):
 
    x = 0
 
    for i in range(len(Q)):
        if (Q[i].first == 1):
            x = getCount(arr, n, Q[i].second.first,
                                 Q[i].second.second)
            print(x, end = " ")
        else:
            setElement(arr, n, Q[i].second.first,
                               Q[i].second.second)
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 2, 2, 3, 4, 4, 5, 6 ]
    n = len(arr)
 
    Q = [ Pair(1, Pair(3, 5)),
          Pair(1, Pair(2, 4)),
          Pair(1, Pair(1, 2)),
          Pair(2, Pair(1, 7)),
          Pair(1, Pair(1, 2)) ]
           
    SolveQuery(arr, n, Q)
 
# This code is contributed by sanjeev2552


C#
// C# code for queries for number
// of elements that lie in range
// [l, r] (with updates)
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to set arr[index] = x
static void setElement(int[] arr, int n,
                       int index, int x)
{
    arr[index] = x;
}
 
// Function to get count of elements
// that lie in range [l, r]
static int getCount(int[] arr, int n,
                    int l, int r)
{
    int count = 0;
     
    // Traverse array
    for(int i = 0; i < n; i++)
    {
         
        // If element lies in the
        // range [L, R]
        if (arr[i] >= l && arr[i] <= r)
         
            // Increase count
            count += 1;
    }
    return count;
}
 
// Function to solve each query
static void SolveQuery(int[] arr, int n,
             List> Q)
{
    int x;
 
    for(int i = 0; i < Q.Count; i++)
    {
        if (Q[i][0] == 1)
        {
            x = getCount(arr, n,
                         Q[i][1],
                         Q[i][2]);
 
            Console.Write(x + " ");
        }
        else
        {
            setElement(arr, n,
                       Q[i][1],
                       Q[i][2]);
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int[] arr = { 1, 2, 2, 3, 4, 4, 5, 6 };
    int n = arr.Length;
 
    List> myList = new List>();
    myList.Add(new List{ 1, 3, 5 });
    myList.Add(new List{ 1, 2, 4 });
    myList.Add(new List{ 1, 1, 2 });
    myList.Add(new List{ 2, 1, 7 });
    myList.Add(new List{ 1, 1, 2 });
 
    SolveQuery(arr, n, myList);
}
}
 
// This code is contributed by grand_master


C++
// C++ code for queries for number
// of elements that lie in range
// [l, r] (with updates)
#include 
using namespace std;
 
class FenwickTree {
public:
    int* BIT;
    int N;
 
    FenwickTree(int N)
    {
        this->N = N;
        BIT = new int[N];
        for (int i = 0; i < N; i++) {
            BIT[i] = 0;
        }
    }
 
    // Traverse all ancestors and
    // increase frequency of index
    void update(int index, int increment)
    {
        while (index < N) {
 
            // Increase count of the current
            // node of BIT Tree
            BIT[index] += increment;
 
            // Update index to that of parent
            // in update View
            index += (index & -index);
        }
    }
    // Function to return the
    // sum of arr[0..index]
    int getSum(int index)
    {
        int sum = 0;
 
        // Traverse ancestors of
        // BITree[index]
        while (index > 0) {
 
            // Add current element of
            // BITree to sum
            sum += BIT[index];
 
            // Move index to parent node in
            // getSum View
            index -= (index & -index);
        }
        return sum;
    }
};
 
// Function to set arr[index] = x
void setElement(int* arr, int n,
                int index, int x,
                FenwickTree* fenTree)
{
    int removedElement = arr[index];
    fenTree->update(removedElement, -1);
    arr[index] = x;
    fenTree->update(x, 1);
}
 
// Function to get count of
// elements that lie in
// range [l, r]
int getCount(int* arr, int n,
            int l, int r,
            FenwickTree* fenTree)
{
    int count = fenTree->getSum(r)
                - fenTree->getSum(l - 1);
    return count;
}
 
// Function to solve each query
void SolveQuery(int arr[], int n,
                vector > >
                    Q)
{
    int N = 100001;
 
    FenwickTree* fenTree = new FenwickTree(N);
 
    for (int i = 0; i < n; i++) {
        fenTree->update(arr[i], 1);
    }
 
    int x;
 
    for (int i = 0; i < Q.size(); i++) {
        if (Q[i].first == 1) {
            x = getCount(arr, n,
                        Q[i].second.first,
                        Q[i].second.second,
                        fenTree);
 
            cout << x << " ";
        }
        else {
            setElement(arr, n,
                    Q[i].second.first,
                    Q[i].second.second,
                    fenTree);
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 2, 3,
                4, 4, 5, 6 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
    vector > > Q
        = { { 1, { 3, 5 } },
            { 1, { 2, 4 } },
            { 1, { 1, 2 } },
            { 2, { 1, 7 } },
            { 1, { 1, 2 } } };
 
    SolveQuery(arr, n, Q);
 
    return 0;
}


输出:
4 5 3 2

时间复杂度: O(Q * N)
辅助空间: O(1)

高效方法:
可以使用Fenwick树优化上述方法。请按照以下步骤解决问题:

  • 从给定的数组构造一个Fenwick树。
  • Fenwick树将被表示为大小等于数组中最大元素的数组,以便可以将数组元素用作索引(想法类似于此方法)。
  • 通过调用Fenwick树的update方法遍历数组并增加每个元素的频率。
  • 对于类型(1 LR)的每个查询,调用Fenwick树的getSum方法。类型1的查询的答案将是:
  • 对于类型(2 ix)的每个查询,调用Fenwick树的update方法以增加添加的元素的频率并减少要替换的元素的数量。

下面是上述方法的实现:

C++

// C++ code for queries for number
// of elements that lie in range
// [l, r] (with updates)
#include 
using namespace std;
 
class FenwickTree {
public:
    int* BIT;
    int N;
 
    FenwickTree(int N)
    {
        this->N = N;
        BIT = new int[N];
        for (int i = 0; i < N; i++) {
            BIT[i] = 0;
        }
    }
 
    // Traverse all ancestors and
    // increase frequency of index
    void update(int index, int increment)
    {
        while (index < N) {
 
            // Increase count of the current
            // node of BIT Tree
            BIT[index] += increment;
 
            // Update index to that of parent
            // in update View
            index += (index & -index);
        }
    }
    // Function to return the
    // sum of arr[0..index]
    int getSum(int index)
    {
        int sum = 0;
 
        // Traverse ancestors of
        // BITree[index]
        while (index > 0) {
 
            // Add current element of
            // BITree to sum
            sum += BIT[index];
 
            // Move index to parent node in
            // getSum View
            index -= (index & -index);
        }
        return sum;
    }
};
 
// Function to set arr[index] = x
void setElement(int* arr, int n,
                int index, int x,
                FenwickTree* fenTree)
{
    int removedElement = arr[index];
    fenTree->update(removedElement, -1);
    arr[index] = x;
    fenTree->update(x, 1);
}
 
// Function to get count of
// elements that lie in
// range [l, r]
int getCount(int* arr, int n,
            int l, int r,
            FenwickTree* fenTree)
{
    int count = fenTree->getSum(r)
                - fenTree->getSum(l - 1);
    return count;
}
 
// Function to solve each query
void SolveQuery(int arr[], int n,
                vector > >
                    Q)
{
    int N = 100001;
 
    FenwickTree* fenTree = new FenwickTree(N);
 
    for (int i = 0; i < n; i++) {
        fenTree->update(arr[i], 1);
    }
 
    int x;
 
    for (int i = 0; i < Q.size(); i++) {
        if (Q[i].first == 1) {
            x = getCount(arr, n,
                        Q[i].second.first,
                        Q[i].second.second,
                        fenTree);
 
            cout << x << " ";
        }
        else {
            setElement(arr, n,
                    Q[i].second.first,
                    Q[i].second.second,
                    fenTree);
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 2, 3,
                4, 4, 5, 6 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
    vector > > Q
        = { { 1, { 3, 5 } },
            { 1, { 2, 4 } },
            { 1, { 1, 2 } },
            { 2, { 1, 7 } },
            { 1, { 1, 2 } } };
 
    SolveQuery(arr, n, Q);
 
    return 0;
}
输出:
4 5 3 2

时间复杂度: O(n * log(N)+ Q * log(N))
辅助空间: O(maxm),其中maxm是数组中存在的最大元素。

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。