Consultas para actualizar los elementos de la array en un rango [L, R] para satisfacer las condiciones dadas

Dada una array arr[] que consta de N 0 s y una array Q[][] con cada fila de la forma (L, R) ., la tarea de cada consulta es actualizar todos los elementos de la array en el rango [L, R] tal que arr[i] = i – L + 1 .

Ejemplos:

Entrada: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 2 }, { 0, 1 } } 
Salida: 1 3 2 0 
Explicación: 
Consulta 1: Actualización de arr[1] = 1 – 1 + 1, arr[2] = 2 – 1 + 1 modifica arr[] a { 0, 1, 2, 0 } 
Consulta2: Actualización de arr[0] = 0 – 0 + 1, arr[1] = 1 – 0 + 1 modifica arr[] a { 1, 3, 2, 0 } 
Por lo tanto, la salida requerida es 1 3 2 0.

Entrada: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 3 }, { 0, 1 } }
Salida: 1 3 2 3

Enfoque ingenuo: el enfoque más simple para resolver el problema es recorrer la array Q[][] y, para cada consulta, recorrer todos los elementos de la array en el rango dado y actualizar arr[i] += i – L + 1 . Finalmente, imprima los elementos de la array. 

Complejidad temporal: O(N * Q)
Espacio auxiliar: O(1)

Enfoque eficiente: el enfoque anterior se puede optimizar utilizando el concepto de array de diferencia . Siga los pasos a continuación para resolver el problema:

  • Inicialice dos arrays arr1[] y arr2[] e inicialice todos los elementos como 0 .
  • Atraviese la array de consultas , Q[][] . Para cada consulta de tipo (L, R) actualice arr1[L] += 1 , arr1[R + 1] -= 1 y arr2[R + 1] -= R – L + 1 .
  • Recorra la array , arr1[] y almacene la suma del prefijo de arr1[] , es decir, arr1[i] += arr1[i -1] .
  • Recorra la array , arr2[] y actualice arr2[i] += arr2[i – 1] + arr1[i] .
  • Finalmente, imprima la array, arr2[] .

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the array
void printArray(int arr[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << arr[i] << " ";
    }
}
 
// Function to perform the query in range [L, R]
// such that arr[i] += i - L + 1
void modifyArray(int arr[], int N, int Q[][2],
                 int cntQuery)
{
 
    // Initialize array
    int arr1[N + 1] = { 0 };
    int arr2[N + 1] = { 0 };
 
    // Traverse the query array
    for (int i = 0; i < cntQuery; i++) {
 
        // Stores range in 1-based index
        int L = Q[i][0] + 1, R = Q[i][1] + 1;
 
        // Update arr1[L]
        arr1[L]++;
 
        // Update arr1[R + 1]
        arr1[R + 1]--;
 
        // Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1;
    }
 
    // Calculate prefix sum
    for (int i = 1; i <= N; i++)
        arr1[i] += arr1[i - 1];
 
    // Traverse the array, arr2[]
    for (int i = 1; i <= N; i++)
        arr2[i] += arr2[i - 1] + arr1[i];
 
    // Copy arr2[] into arr[]
    for (int i = 1; i <= N; i++)
        arr[i - 1] = arr2[i];
 
    printArray(arr, N);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 0, 0, 0, 0 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int Q[][2] = { { 1, 3 }, { 0, 1 } };
 
    // Stores count of query
    int cntQuery
        = sizeof(Q) / sizeof(Q[0]);
 
    // Function Call
    modifyArray(arr, N, Q, cntQuery);
 
    return 0;
}

Java

// Java program to implement
// the above approach
class GFG
{
 
    // Function to print the array
    static void printArray(int arr[], int N)
    {
        for (int i = 0; i < N; i++)
        {
            System.out.print(arr[i] + " ");
        }
    }
     
    // Function to perform the query in range [L, R]
    // such that arr[i] += i - L + 1
    static void modifyArray(int arr[], int N, int Q[][],
                     int cntQuery)
    {
     
        // Initialize array
        int arr1[] = new int[N + 2];
        int arr2[] = new int[N + 2];
     
        // Traverse the query array
        for (int i = 0; i < cntQuery; i++)
        {
     
            // Stores range in 1-based index
            int L = Q[i][0] + 1, R = Q[i][1] + 1;
     
            // Update arr1[L]
            arr1[L]++;
     
            // Update arr1[R + 1]
            arr1[R + 1]--;
     
            // Update arr2[R + 1]
            arr2[R + 1] -= R - L + 1;
        }
     
        // Calculate prefix sum
        for (int i = 1; i <= N; i++)
            arr1[i] += arr1[i - 1];
     
        // Traverse the array, arr2[]
        for (int i = 1; i <= N; i++)
            arr2[i] += arr2[i - 1] + arr1[i];
     
        // Copy arr2[] into arr[]
        for (int i = 1; i <= N; i++)
            arr[i - 1] = arr2[i];   
        printArray(arr, N);
    }
     
    // Driver Code
    public static void main (String[] args)
    {
       
        // Given array
        int arr[] = { 0, 0, 0, 0 };
     
        // Size of the array
        int N = arr.length;   
        int Q[][] = { { 1, 3 }, { 0, 1 } };
     
        // Stores count of query
        int cntQuery = Q.length;
     
        // Function Call
        modifyArray(arr, N, Q, cntQuery);
    }
}
 
// This code is contributed by AnkThon

Python3

# Python3 program to implement
# the above approach
 
# Function to print array
def printArray(arr, N):
    print(*arr)
 
# Function to perform the query in range [L, R]
# such that arr[i] += i - L + 1
def modifyArray(arr, N, Q, cntQuery):
 
    # Initialize array
    arr1 = [0 for i in range(N + 2)]
    arr2 = [0 for i in range(N + 2)]
 
    # Traverse the query array
    for i in range(cntQuery):
 
        # Stores range in 1-based index
        L = Q[i][0] + 1
        R = Q[i][1] + 1
        # print(L,R)
 
        # Update arr1[L]
        arr1[L] += 1
 
        # Update arr1[R + 1]
        arr1[R + 1] -= 1
 
        # Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1
 
    # Calculate prefix sum
    for i in range(1, N + 1):
        arr1[i] += arr1[i - 1]
 
    # Traverse the array, arr2[]
    for i in range(1, N + 1):
        arr2[i] += arr2[i - 1] + arr1[i]
 
    # Copy arr2[] into arr[]
    for i in range(1, N + 1):
        arr[i - 1] = arr2[i]
    printArray(arr, N)
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [0, 0, 0, 0]
 
    # Size of the array
    N = len(arr)
    Q = [[ 1, 3 ], [ 0, 1 ]]
 
    # Stores count of query
    cntQuery = len(Q)
 
    # Function Call
    modifyArray(arr, N, Q, cntQuery)
 
# This code is contributed by mohit kumar 29.

C#

// C# program to implement
// the above approach
using System;
class GFG
{
 
    // Function to print the array
    static void printArray(int []arr, int N)
    {
        for (int i = 0; i < N; i++)
        {
            Console.Write(arr[i] + " ");
        }
    }
     
    // Function to perform the query in range [L, R]
    // such that arr[i] += i - L + 1
    static void modifyArray(int []arr, int N, int[,] Q,
                     int cntQuery)
    {
     
        // Initialize array
        int []arr1 = new int[N + 2];
        int []arr2 = new int[N + 2];
     
        // Traverse the query array
        for (int i = 0; i < cntQuery; i++)
        {
     
            // Stores range in 1-based index
            int L = Q[i,0] + 1, R = Q[i,1] + 1;
     
            // Update arr1[L]
            arr1[L]++;
     
            // Update arr1[R + 1]
            arr1[R + 1]--;
     
            // Update arr2[R + 1]
            arr2[R + 1] -= R - L + 1;
        }
     
        // Calculate prefix sum
        for (int i = 1; i <= N; i++)
            arr1[i] += arr1[i - 1];
     
        // Traverse the array, arr2[]
        for (int i = 1; i <= N; i++)
            arr2[i] += arr2[i - 1] + arr1[i];
     
        // Copy arr2[] into arr[]
        for (int i = 1; i <= N; i++)
            arr[i - 1] = arr2[i];   
        printArray(arr, N);
    }
     
    // Driver Code
    public static void Main()
    {
       
        // Given array
        int []arr = { 0, 0, 0, 0 };
     
        // Size of the array
        int N = arr.Length;   
        int [,]Q = { { 1, 3 }, { 0, 1 } };
     
        // Stores count of query
        int cntQuery = 2;
     
        // Function Call
        modifyArray(arr, N, Q, cntQuery);
    }
}
 
// This code is contributed by bgangwar59.

Javascript

<script>
 
// Javascript program to implement
// the above approach
 
// Function to print the array
function printArray(arr, N)
{
    for(let i = 0; i < N; i++)
    {
        document.write(arr[i] + " ");
    }
}
 
// Function to perform the query in
// range [L, R] such that
// arr[i] += i - L + 1
function modifyArray(arr, N, Q, cntQuery)
{
 
    // Initialize array
    let arr1 = new Array(N + 2).fill(0);
    let arr2 = new Array(N + 2).fill(0);
     
    // Traverse the query array
    for(let i = 0; i < cntQuery; i++)
    {
     
        // Stores range in 1-based index
        let L = Q[i][0] + 1, R = Q[i][1] + 1;
         
        // Update arr1[L]
        arr1[L]++;
         
        // Update arr1[R + 1]
        arr1[R + 1]--;
         
        // Update arr2[R + 1]
        arr2[R + 1] -= R - L + 1;
    }
     
    // Calculate prefix sum
    for(let i = 1; i <= N; i++)
        arr1[i] += arr1[i - 1];
     
    // Traverse the array, arr2[]
    for(let i = 1; i <= N; i++)
        arr2[i] += arr2[i - 1] + arr1[i];
     
    // Copy arr2[] into arr[]
    for(let i = 1; i <= N; i++)
        arr[i - 1] = arr2[i];  
         
    prletArray(arr, N);
}
 
// Driver Code
 
// Given array
let arr = [ 0, 0, 0, 0 ];
 
// Size of the array
let N = arr.length;  
let Q = [ [ 1, 3 ], [ 0, 1 ] ];
 
// Stores count of query
let cntQuery = Q.length;
 
// Function Call
modifyArray(arr, N, Q, cntQuery);
 
// This code is contributed by avijitmondal1998
 
</script>
Producción: 

1 3 2 3

 

Complejidad temporal: O(N+Q)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por pushpendrayadav1057 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *