📌  相关文章
📜  将给定范围内的数组元素按给定值递增给定次数的查询

📅  最后修改于: 2021-09-06 11:06:50             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[]和形式为{a, b, val, f} 的M 个查询。任务是在执行每个查询后打印数组,以将[a, b]范围内的数组元素增加值val f次。

例子:

朴素的方法最简单的方法是在给定的数组上执行每个查询,即,对于每个查询{a, b, val, f}在范围[a, b] 上遍历数组并通过值val将每个元素增加到f数次。执行每个查询后打印数组。

时间复杂度: O(N * M * max(Freq))
辅助空间: O(1)

更好的方法这个想法基于可以在范围更新操作中使用的差异数组。以下是步骤:

  1. 求给定数组A[]的差分数组D[]定义为D[i] = (A[i] – A[i – 1]) (0 < i < N) 和D[0] = A[ 0]考虑基于0的索引。
  2. val添加到D[a – 1]并从D[(b – 1) + 1] 中减去它,即D[a – 1] += val, D[(b – 1) + 1] -= val。执行此操作Freq次数。
  3. 现在使用差异数组更新给定数组。将 A[0]更新为D[0]并打印出来。对于其余元素,执行A[i] = A[i-1] + D[i]
  4. 在上述步骤后打印结果数组。

时间复杂度: O(N + M * max(Freq))
辅助空间: O(N)差分数组的额外空间

高效的方法这种方法类似于以前的方法,但是是差分数组应用程序的扩展版本。以前的任务是将值从索引a更新到bvalf次。这里不是调用范围更新函数f次,而是为每个查询只调用一次:

  1. 通过val*f更新从索引ab的值,每个查询只更新 1 次。
  2. val*fD[a – 1]相加并从D[(b – 1) + 1] 中减去,即D[a – 1]增加val*fD[b]减少val*f .
  3. 现在使用差异数组更新主数组。将 A[0]更新为D[0]并打印出来。
  4. 对于其余元素,通过(A[i-1] + D[i])更新A[i]
  5. 在上述步骤后打印结果数组。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function that creates a difference
// array D[] for A[]
vector initializeDiffArray(
    vector& A)
{
    int N = A.size();
 
    // Stores the difference array
    vector D(N + 1);
 
    D[0] = A[0], D[N] = 0;
 
    // Update difference array D[]
    for (int i = 1; i < N; i++)
        D[i] = A[i] - A[i - 1];
 
    // Return difference array
    return D;
}
 
// Function that performs the range
// update queries
void update(vector& D, int l,
            int r, int x)
{
    // Update the ends of the range
    D[l] += x;
    D[r + 1] -= x;
}
 
// Function that perform all query
// once with modified update Call
void UpdateDiffArray(vector& DiffArray,
                     int Start, int End,
                     int Val, int Freq)
{
    // For range update, difference
    // array is modified
    update(DiffArray, Start - 1,
           End - 1, Val * Freq);
}
 
// Function to take queries
void queriesInput(vector& DiffArray,
                  int Q[][4], int M)
{
    // Traverse the query
    for (int i = 0; i < M; i++) {
 
        // Function Call for updates
        UpdateDiffArray(DiffArray, Q[i][0],
                        Q[i][1], Q[i][2],
                        Q[i][3]);
    }
}
 
// Function to updates the array
// using the difference array
void UpdateArray(vector& A,
                 vector& D)
{
    // Traverse the array A[]
    for (int i = 0; i < A.size(); i++) {
 
        // 1st Element
        if (i == 0) {
            A[i] = D[i];
        }
 
        // A[0] or D[0] decides values
        // of rest of the elements
        else {
            A[i] = D[i] + A[i - 1];
        }
    }
}
 
// Function that prints the array
void PrintArray(vector& A)
{
    // Print the element
    for (int i = 0; i < A.size(); i++) {
        cout << A[i] << " ";
    }
 
    return;
}
 
// Function that print the array
// after performing all queries
void printAfterUpdate(vector& A,
                      int Q[][4], int M)
{
    // Create and fill difference
    // array for range updates
    vector DiffArray
        = initializeDiffArray(A);
 
    queriesInput(DiffArray, Q, M);
 
    // Now update Array A using
    // Difference Array
    UpdateArray(A, DiffArray);
 
    // Print updated Array A
    // after M queries
    PrintArray(A);
}
 
// Driver Code
int main()
{
    // N = Array size, M = Queries
    int N = 3, M = 3;
 
    // Given array A[]
    vector A{ 1, 2, 3 };
 
    // Queries
    int Q[][4] = { { 1, 2, 1, 4 },
                   { 1, 3, 2, 3 },
                   { 2, 3, 4, 5 } };
 
    // Function Call
    printAfterUpdate(A, Q, M);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
   
// N = Array size,
// M = Queries
static int N = 3, M = 3;
   
static int []A = new int[N];
 
//Stores the difference array
static int []D = new int[N + 1];
   
// Function that creates
// a difference array D[]
// for A[]
static void initializeDiffArray()
{
  D[0] = A[0];
  D[N] = 0;
 
  // Update difference array D[]
  for (int i = 1; i < N; i++)
    D[i] = A[i] - A[i - 1];
}
 
// Function that performs
// the range update queries
static void update(int l,
                   int r, int x)
{
  // Update the ends
  // of the range
  D[l] += x;
  D[r + 1] -= x;
}
 
// Function that perform all query
// once with modified update Call
static void UpdateDiffArray(int Start, int End,
                            int Val, int Freq)
{
  // For range update, difference
  // array is modified
  update(Start - 1,
         End - 1, Val * Freq);
}
 
// Function to take queries
static void queriesInput(  int Q[][])
{
  // Traverse the query
  for (int i = 0; i < M; i++)
  {
    // Function Call for updates
    UpdateDiffArray(Q[i][0], Q[i][1],
                    Q[i][2], Q[i][3]);
  }
}
 
// Function to updates the array
// using the difference array
static void UpdateArray()
{
  // Traverse the array A[]
  for (int i = 0; i < N; i++)
  {
    // 1st Element
    if (i == 0)
    {
      A[i] = D[i];
    }
 
    // A[0] or D[0] decides
    // values of rest of
    // the elements
    else
    {
      A[i] = D[i] + A[i - 1];
    }
  }
}
 
// Function that prints
// the array
static void PrintArray()
{
  // Print the element
  for (int i = 0; i < N; i++)
  {
    System.out.print(A[i] + i +
                     1 + " ");
  }
  return;
}
 
// Function that print the array
// after performing all queries
static void printAfterUpdate(int []A,
                             int Q[][], int M)
{
  // Create and fill difference
  // array for range updates
  initializeDiffArray();
 
  queriesInput( Q);
 
  // Now update Array
  // A using Difference
  // Array
  UpdateArray();
 
  // Print updated Array A
  // after M queries
  PrintArray();
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array A[]
  int []A = {1, 2, 3};
 
  // Queries
  int [][]Q = {{1, 2, 1, 4},
               {1, 3, 2, 3},
               {2, 3, 4, 5}};
 
  // Function Call
  printAfterUpdate(A, Q, M);
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
 
# Function that creates a difference
# array D[] for A[]
def initializeDiffArray(A):
     
    N = len(A)
 
    # Stores the difference array
    D = [0] * (N + 1)
 
    D[0] = A[0]
    D[N] = 0
 
    # Update difference array D[]
    for i in range(1, N):
        D[i] = A[i] - A[i - 1]
 
    # Return difference array
    return D
 
# Function that performs the range
# update queries
def update(D, l, r, x):
     
    # Update the ends of the range
    D[l] += x
    D[r + 1] -= x
 
# Function that perform all query
# once with modified update Call
def UpdateDiffArray(DiffArray, Start,
                    End, Val, Freq):
                         
    # For range update, difference
    # array is modified
    update(DiffArray, Start - 1,
           End - 1, Val * Freq)
 
# Function to take queries
def queriesInput(DiffArray, Q, M):
     
    # Traverse the query
    for i in range(M):
 
        # Function Call for updates
        UpdateDiffArray(DiffArray, Q[i][0],
                          Q[i][1], Q[i][2],
                          Q[i][3])
 
# Function to updates the array
# using the difference array
def UpdateArray(A, D):
     
    # Traverse the array A[]
    for i in range(len(A)):
 
        # 1st Element
        if (i == 0):
            A[i] = D[i]
 
        # A[0] or D[0] decides values
        # of rest of the elements
        else:
            A[i] = D[i] + A[i - 1]
 
# Function that prints the array
def PrintArray(A):
     
    # Print the element
    for i in range(len(A)):
        print(A[i], end = " ")
         
    return
 
# Function that print the array
# after performing all queries
def printAfterUpdate(A, Q, M):
     
    # Create and fill difference
    # array for range updates
    DiffArray = initializeDiffArray(A)
 
    queriesInput(DiffArray, Q, M)
 
    # Now update Array A using
    # Difference Array
    UpdateArray(A, DiffArray)
 
    # Prupdated Array A
    # after M queries
    PrintArray(A)
 
# Driver Code
if __name__ == '__main__':
     
    # N = Array size, M = Queries
    N = 3
    M = 3
 
    # Given array A[]
    A = [ 1, 2, 3 ]
 
    # Queries
    Q = [ [ 1, 2, 1, 4 ],
          [ 1, 3, 2, 3 ],
          [ 2, 3, 4, 5 ] ]
 
    # Function call
    printAfterUpdate(A, Q, M)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
class GFG{
 
// N = Array size,
// M = Queries
static int N = 3, M = 3;
 
static int[] A = new int[N];
 
// Stores the difference array
static int[] D = new int[N + 1];
 
// Function that creates
// a difference array D[]
// for A[]
static void initializeDiffArray()
{
  D[0] = A[0];
  D[N] = 0;
 
  // Update difference array D[]
  for (int i = 1; i < N; i++)
    D[i] = A[i] - A[i - 1];
}
 
// Function that performs
// the range update queries
static void update(int l,
                   int r, int x)
{
  // Update the ends
  // of the range
  D[l] += x;
  D[r + 1] -= x;
}
 
// Function that perform all query
// once with modified update Call
static void UpdateDiffArray(int Start, int End,
                            int Val, int Freq)
{
  // For range update, difference
  // array is modified
  update(Start - 1,
         End - 1, Val * Freq);
}
 
// Function to take queries
static void queriesInput(int[, ] Q)
{
  // Traverse the query
  for (int i = 0; i < M; i++)
  {
    // Function Call for updates
    UpdateDiffArray(Q[i, 0], Q[i, 1],
                    Q[i, 2], Q[i, 3]);
  }
}
 
// Function to updates the array
// using the difference array
static void UpdateArray()
{
  // Traverse the array A[]
  for (int i = 0; i < N; i++)
  {
    // 1st Element
    if (i == 0)
    {
      A[i] = D[i];
    }
 
    // A[0] or D[0] decides
    // values of rest of
    // the elements
    else
    {
      A[i] = D[i] + A[i - 1];
    }
  }
}
 
// Function that prints
// the array
static void PrintArray()
{
  // Print the element
  for (int i = 0; i < N; i++)
  {
    Console.Write(A[i] + i +
                  1 + " ");
  }
  return;
}
 
// Function that print the array
// after performing all queries
static void printAfterUpdate(int[] A,
                             int[, ] Q, int M)
{
  // Create and fill difference
  // array for range updates
  initializeDiffArray();
 
  queriesInput(Q);
 
  // Now update Array
  // A using Difference
  // Array
  UpdateArray();
 
  // Print updated Array A
  // after M queries
  PrintArray();
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array A[]
  int[] A = {1, 2, 3};
 
  // Queries
  int[, ] Q = {{1, 2, 1, 4},
               {1, 3, 2, 3},
               {2, 3, 4, 5}};
 
  // Function Call
  printAfterUpdate(A, Q, M);
}
 
// This code is contributed by Chitranayal


Javascript


输出
11 32 29 

时间复杂度: O(N + M)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live