Recuento de trillizos de sumas pares en la array para consultas de rango Q

Dada una array arr[] de tamaño N y Q consultas de la forma (L, R) , la tarea es contar el número de tripletes con una suma uniforme para los elementos en el rango L y R para cada consulta.

Ejemplos:

Entrada: N = 6 , arr[ ] = {1, 2, 3, 4, 5, 6}, Q[ ] = {{1, 3}, {2, 5}}
Salida: 1 2
Explicación:
Para consulta ( 1, 3): solo existe el triplete (1, 2, 3) con suma par
Para consulta (2, 5): los tripletes (2, 3, 5) y (3, 4, 5) tienen suma par. 
Por lo tanto, la salida es 1 y 2 respectivamente

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

 

Enfoque: el problema anterior se puede resolver con las observaciones de que para que la suma de un triplete sea par, los elementos deben ser uno de los siguientes patrones:
 

  • par + par + par = par
  • impar + impar + par = par 

Siga los pasos a continuación para resolver el problema:

  • Inicialice dos arrays , digamos arr_even[] y arr_odd[] de tamaño de longitud + 1 .
  • Inicialice las variables, digamos par = 0 e impar = 0 , para almacenar el recuento de números pares e impares.
  • Recorra la array arr[] y para cada i almacene números pares hasta el índice i en arr_even[i] y números impares hasta el índice i en arr_odd[i] .
  • Iterar sobre las consultas Q[] y para cada par (l, r) :
    • Encuentre el recuento de números pares en (l, r) como arr_par[r] – arr_par[l-1] y el recuento de números impares en (l, r) como arr_odd[r] – arr_odd[l-1].
    • Encuentre el recuento de trillizos en la variable, por ejemplo , como suma de ( par*(par-1)*(par-2))/6 e (impar*(impar-1)/2)*par.
    • Finalmente, imprima las respuestas para cada consulta.

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

C++

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count number of triplets
// with even sum in range l, r for each
// query
void countTriplets(int size, int queries,
                   int arr[], int Q[][2])
{
 
    // Initialization of array
    int arr_even[size + 1], arr_odd[size + 1];
 
    // Initialization of variables
    int even = 0, odd = 0;
    arr_even[0] = 0;
    arr_odd[0] = 0;
 
    // Traversing array
    for (int i = 0; i < size; i++) {
 
        // If element is odd
        if (arr[i] % 2) {
            odd++;
        }
 
        // If element is even
        else {
            even++;
        }
 
        // Storing count of even and odd
        // till each i
        arr_even[i + 1] = even;
        arr_odd[i + 1] = odd;
    }
 
    // Traversing each query
    for (int i = 0; i < queries; i++) {
        int l = Q[i][0], r = Q[i][1];
 
        // Count of odd numbers in l to r
        int odd = arr_odd[r] - arr_odd[l - 1];
 
        // Count of even numbers in l to r
        int even = arr_even[r] - arr_even[l - 1];
 
        // Finding the ans
        int ans = (even * (even - 1)
                   * (even - 2))
                      / 6
                  + (odd * (odd - 1) / 2)
                        * even;
 
        // Printing the ans
        cout << ans << " ";
    }
}
 
// Driver Code
int main()
{
    // Given Input
    int N = 6, Q = 2;
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int queries[][2] = { { 1, 3 }, { 2, 5 } };
 
    // Function Call
    countTriplets(N, Q, arr, queries);
 
    return 0;
}

Java

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    // Function to count number of triplets
    // with even sum in range l, r for each
    // query
    static void countTriplets(int size, int queries,
                              int[] arr, int[][] Q)
    {
 
        // Initialization of array
        int[] arr_even = new int[size + 1];
        int []arr_odd = new int[size + 1];
 
        // Initialization of variables
        int even = 0;
      int odd = 0;
        arr_even[0] = 0;
        arr_odd[0] = 0;
 
        // Traversing array
        for (int i = 0; i < size; i++) {
 
            // If element is odd
            if (arr[i] % 2 == 1) {
                odd++;
            }
 
            // If element is even
            else {
                even++;
            }
 
            // Storing count of even and odd
            // till each i
            arr_even[i + 1] = even;
            arr_odd[i + 1] = odd;
        }
 
        // Traversing each query
        for (int i = 0; i < queries; i++) {
            int l = Q[i][0], r = Q[i][1];
 
            // Count of odd numbers in l to r
             odd = arr_odd[r] - arr_odd[l - 1];
 
            // Count of even numbers in l to r
             even = arr_even[r] - arr_even[l - 1];
 
            // Finding the ans
            int ans = (even * (even - 1) * (even - 2)) / 6
                      + (odd * (odd - 1) / 2) * even;
 
            // Printing the ans
            System.out.print(ans + " ");
        }
    }
 
    // Driver Code
 
    public static void main(String[] args)
    {
        // Given Input
        int N = 6, Q = 2;
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int[][] queries = { { 1, 3 }, { 2, 5 } };
        countTriplets(N, Q, arr, queries);
    }
}
 
// This code is contributed by maddler.

Python3

# Python 3 program for above approach
 
# Function to count number of triplets
# with even sum in range l, r for each
# query
def countTriplets(size, queries, arr, Q):
   
    # Initialization of array
    arr_even = [0 for i in range(size + 1)]
    arr_odd = [0 for i in range(size + 1)]
 
    # Initialization of variables
    even = 0
    odd = 0
    arr_even[0] = 0
    arr_odd[0] = 0
 
    # Traversing array
    for i in range(size):
       
        # If element is odd
        if (arr[i] % 2):
            odd += 1
 
        # If element is even
        else:
            even += 1
 
        # Storing count of even and odd
        # till each i
        arr_even[i + 1] = even
        arr_odd[i + 1] = odd
 
    # Traversing each query
    for i in range(queries):
        l = Q[i][0]
        r = Q[i][1]
 
        # Count of odd numbers in l to r
        odd = arr_odd[r] - arr_odd[l - 1]
 
        # Count of even numbers in l to r
        even = arr_even[r] - arr_even[l - 1]
 
        # Finding the ans
        ans = (even * (even - 1)*(even - 2)) // 6 + (odd * (odd - 1) // 2)* even
 
        # Printing the ans
        print(ans,end = " ")
 
# Driver Code
if __name__ == '__main__':
    # Given Input
    N = 6
    Q = 2
    arr = [1, 2, 3, 4, 5, 6]
    queries = [[1, 3],[2, 5]]
 
    # Function Call
    countTriplets(N, Q, arr, queries)
     
    # This code is contributed by ipg2016107.

C#

// C# program for above approach
using System;
 
class GFG
{
   
    // Function to count number of triplets
    // with even sum in range l, r for each
    // query
    static void countTriplets(int size, int queries,
                              int[] arr, int[, ] Q)
    {
 
        // Initialization of array
        int[] arr_even = new int[size + 1];
        int[] arr_odd = new int[size + 1];
 
        // Initialization of variables
        int even = 0;
        int odd = 0;
        arr_even[0] = 0;
        arr_odd[0] = 0;
 
        // Traversing array
        for (int i = 0; i < size; i++) {
 
            // If element is odd
            if (arr[i] % 2 == 1) {
                odd++;
            }
 
            // If element is even
            else {
                even++;
            }
 
            // Storing count of even and odd
            // till each i
            arr_even[i + 1] = even;
            arr_odd[i + 1] = odd;
        }
 
        // Traversing each query
        for (int i = 0; i < queries; i++) {
            int l = Q[i, 0], r = Q[i, 1];
 
            // Count of odd numbers in l to r
            odd = arr_odd[r] - arr_odd[l - 1];
 
            // Count of even numbers in l to r
            even = arr_even[r] - arr_even[l - 1];
 
            // Finding the ans
            int ans = (even * (even - 1) * (even - 2)) / 6
                      + (odd * (odd - 1) / 2) * even;
 
            // Printing the ans
            Console.Write(ans + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
       
        // Given Input
        int N = 6, Q = 2;
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int[, ] queries = { { 1, 3 }, { 2, 5 } };
        countTriplets(N, Q, arr, queries);
    }
}
 
// This code is contributed by subham348.

Javascript

  <script>
        // JavaScript Program to implement
        // the above approach
 
    // Function to count number of triplets
    // with even sum in range l, r for each
    // query
    function countTriplets(size, queries, arr, Q)
    {
 
        // Initialization of array
        let arr_even = new Array(size + 1);
        let arr_odd = new Array(size + 1);
 
        // Initialization of variables
        let even = 0;
      let odd = 0;
        arr_even[0] = 0;
        arr_odd[0] = 0;
 
        // Traversing array
        for (let i = 0; i < size; i++) {
 
            // If element is odd
            if (arr[i] % 2 == 1) {
                odd++;
            }
 
            // If element is even
            else {
                even++;
            }
 
            // Storing count of even and odd
            // till each i
            arr_even[i + 1] = even;
            arr_odd[i + 1] = odd;
        }
 
        // Traversing each query
        for (let i = 0; i < queries; i++) {
            let l = Q[i][0], r = Q[i][1];
 
            // Count of odd numbers in l to r
             odd = arr_odd[r] - arr_odd[l - 1];
 
            // Count of even numbers in l to r
             even = arr_even[r] - arr_even[l - 1];
 
            // Finding the ans
            let ans = (even * (even - 1) * (even - 2)) / 6
                      + (odd * (odd - 1) / 2) * even;
 
            // Printing the ans
            document.write(ans + " ");
        }
    }
         
 // Driver Code
         
      // Given Input
        let N = 6, Q = 2;
        let arr = [ 1, 2, 3, 4, 5, 6 ];
        let queries = [[ 1, 3 ], [ 2, 5 ]];
        countTriplets(N, Q, arr, queries);
 
// This code is contributed by sanjoy_62.
    </script>
Producción: 

1 2

 

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

Publicación traducida automáticamente

Artículo escrito por bemypro111 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 *