Dada una array arr[] y una array consulta[] que consta de consultas Q , la tarea para cada i -ésima consulta es contar el número de subarreglos que tienen consulta[i] como último elemento.
Nota: Los subarreglos se considerarán diferentes para diferentes ocurrencias de X.
Ejemplos:
Entrada: arr[] = {1, 5, 4, 5, 6}, Q = 3, query[]={1, 4, 5}
Salida: 1 3 6
Explicación:
Consulta 1: Subarreglos que tienen 1 como último elemento es {1}
Consulta 2: Los subarreglos que tienen 4 como último elemento son {4}, {5, 4}, {1, 5, 4}. Por lo tanto, el recuento es 3.
Consulta 3: los subarreglos que tienen 5 como último elemento son {1, 5}, {5}, {1, 5, 4, 5}, {5}, {4, 5}, {5 , 4, 5}. Por lo tanto, la cuenta es 6.
.
Entrada: arr[] = {1, 2, 3, 3}, Q= 3, consulta[]={3, 1, 2}
Salida: 7 1 2
Enfoque ingenuo: el enfoque más simple para resolver el problema es generar todos los subarreglos para cada consulta y para cada subarreglo, verifique si consta de X como último elemento.
Complejidad de Tiempo: O(Q×N 3 )
Espacio Auxiliar: O(1)
Enfoque eficiente: para optimizar el enfoque anterior, la idea es utilizar Hashing. Recorra la array y para cada elemento de la array arr[i] , busque su aparición en la array. Para cada índice, digamos idx , en el que se encuentra arr[i] , agregue (idx+1) al recuento de subarreglos que tienen arr[i] como último elemento.
Siga los pasos a continuación para resolver el problema:
- Inicialice un mapa desordenado , digamos mp, para almacenar el número de subarreglos que tengan X como último elemento.
- Recorra la array y para cada entero arr[i] , aumente mp[arr[i]] en (i+1).
- Recorra la array consulta[] y para cada consulta consulta[i] , imprima mp[consulta[i]].
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to perform queries to count the // number of subarrays having given numbers // as the last integer int subarraysEndingWithX( int arr[], int N, int query[], int Q) { // Stores the number of subarrays having // x as the last element unordered_map<int, int> mp; // Traverse the array for (int i = 0; i < N; i++) { // Stores current array element int val = arr[i]; // Add contribution of subarrays // having arr[i] as last element mp[val] += (i + 1); } // Traverse the array of queries for (int i = 0; i < Q; i++) { int q = query[i]; // Print the count of subarrays cout << mp[q] << " "; } } // Driver Code int main() { // Given array int arr[] = { 1, 5, 4, 5, 6 }; // Number of queries int Q = 3; // Array of queries int query[] = { 1, 4, 5 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); subarraysEndingWithX(arr, N, query, Q); return 0; }
Java
// Java program for the above approach import java.util.*; class GFG{ // Function to perform queries to count the // number of subarrays having given numbers // as the last integer static void subarraysEndingWithX( int arr[], int N, int query[], int Q) { // Stores the number of subarrays having // x as the last element HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse the array for (int i = 0; i < N; i++) { // Stores current array element int val = arr[i]; // Add contribution of subarrays // having arr[i] as last element if(mp.containsKey(val)) mp.put(val, mp.get(val)+(i+1)); else mp.put(val, i+1); } // Traverse the array of queries for (int i = 0; i < Q; i++) { int q = query[i]; // Print the count of subarrays System.out.print(mp.get(q)+ " "); } } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 1, 5, 4, 5, 6 }; // Number of queries int Q = 3; // Array of queries int query[] = { 1, 4, 5 }; // Size of the array int N = arr.length; subarraysEndingWithX(arr, N, query, Q); } } // This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach # Function to perform queries to count the # number of subarrays having given numbers # as the last integer def subarraysEndingWithX(arr, N, query, Q): # Stores the number of subarrays having # x as the last element mp = {} # Traverse the array for i in range(N): # Stores current array element val = arr[i] # Add contribution of subarrays # having arr[i] as last element if val in mp: mp[val] += (i + 1) else: mp[val] = mp.get(val, 0) + (i + 1); # Traverse the array of queries for i in range(Q): q = query[i] # Print the count of subarrays print(mp[q],end = " ") # Driver Code if __name__ == '__main__': # Given array arr = [1, 5, 4, 5, 6] # Number of queries Q = 3 # Array of queries query = [1, 4, 5] # Size of the array N = len(arr) subarraysEndingWithX(arr, N, query, Q) # This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG { // Function to perform queries to count the // number of subarrays having given numbers // as the last integer static void subarraysEndingWithX(int[] arr, int N, int[] query, int Q) { // Stores the number of subarrays having // x as the last element Dictionary<int, int> mp = new Dictionary<int, int>(); // Traverse the array for (int i = 0; i < N; i++) { // Stores current array element int val = arr[i]; // Add contribution of subarrays // having arr[i] as last element if (mp.ContainsKey(val)) mp[val] = mp[val] + (i + 1); else mp[val] = i + 1; } // Traverse the array of queries for (int i = 0; i < Q; i++) { int q = query[i]; // Print the count of subarrays Console.Write(mp[q] + " "); } } // Driver Code public static void Main() { // Given array int[] arr = { 1, 5, 4, 5, 6 }; // Number of queries int Q = 3; // Array of queries int[] query = { 1, 4, 5 }; // Size of the array int N = arr.Length; subarraysEndingWithX(arr, N, query, Q); } } // This code is contributed by chitranayal.
Javascript
<script> // JavaScript program for the above approach // Function to perform queries to count the // number of subarrays having given numbers // as the last integer function subarraysEndingWithX(arr, N, query, Q) { // Stores the number of subarrays having // x as the last element let mp = new Map(); // Traverse the array for (let i = 0; i < N; i++) { // Stores current array element let val = arr[i]; // Add contribution of subarrays // having arr[i] as last element if(mp.has(val)) mp.set(val, mp.get(val)+(i+1)); else mp.set(val, i+1); } // Traverse the array of queries for (let i = 0; i < Q; i++) { let q = query[i]; // Print the count of subarrays document.write(mp.get(q)+ " "); } } // Driver Code // Given array let arr = [ 1, 5, 4, 5, 6 ]; // Number of queries let Q = 3; // Array of queries let query = [ 1, 4, 5 ]; // Size of the array let N = arr.length; subarraysEndingWithX(arr, N, query, Q); </script>
1 3 6
Complejidad temporal: O(Q + N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por shubhampokhriyal2018 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA