Dada una array arr[] de N elementos enteros, la tarea es elegir un elemento X y aplicar la operación XOR en cada elemento de la array con X de modo que la suma de la array se minimice.
Entrada: arr[] = {3, 5, 7, 11, 15}
Salida: 26
Representación binaria de los elementos de la array son {0011, 0101, 0111, 1011, 1111}
Tomamos xor de cada elemento con 7 para minimizar la suma.
3 XOR 7 = 0100 (4)
5 XOR 7 = 0010 (2)
7 XOR 7 = 0000 (0)
11 XOR 7 = 1100 (12)
15 XOR 7 = 1000 (8)
Suma = 4 + 2 + 0 + 12 + 8 = 26
Entrada: arr[] = {1, 2, 3, 4, 5}
Salida: 14
Planteamiento: La tarea es encontrar el elemento X con el que tenemos que tomar xor de cada elemento.
- Convierta cada número en forma binaria y actualice la frecuencia del bit (0 o 1) en una array correspondiente a la posición de cada bit en el elemento de la array.
- Ahora, recorra la array y verifique si el elemento en el índice es más de n/2 (para ‘n’ elementos, verificamos si el bit establecido aparece más de n/2 en el índice), y posteriormente, obtenemos el elemento ‘X’
- Ahora, toma xor de ‘X’ con todos los elementos y devuelve la suma.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; const int MAX = 25; // Function to return the minimized sum int getMinSum(int arr[], int n) { int bits_count[MAX], max_bit = 0, sum = 0, ans = 0; memset(bits_count, 0, sizeof(bits_count)); // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code int main() { int arr[] = { 3, 5, 7, 11, 15 }; int n = sizeof(arr) / sizeof(arr[0]); cout << getMinSum(arr, n); return 0; }
Java
// Java implementation of the approach class GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int arr[], int n) { int bits_count[] = new int[MAX], max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void main(String[] args) { int arr[] = { 3, 5, 7, 11, 15 }; int n = arr.length; System.out.println(getMinSum(arr, n)); } } // This code has been contributed by 29AjayKumar
Python3
# Python3 implementation of the approach MAX = 25; # Function to return the minimized sum def getMinSum(arr, n) : bits_count = [0]* MAX max_bit = 0; sum = 0; ans = 0; # To store the frequency # of bit in every element for d in range(n) : e = arr[d]; f = 0; while (e > 0) : rem = e % 2; e = e // 2; if (rem == 1) : bits_count[f] += rem; f += 1 max_bit = max(max_bit, f); # Finding element X for d in range(max_bit) : temp = pow(2, d); if (bits_count[d] > n // 2) : ans = ans + temp; # Taking XOR of elements and finding sum for d in range(n) : arr[d] = arr[d] ^ ans; sum = sum + arr[d]; return sum # Driver code if __name__ == "__main__" : arr = [ 3, 5, 7, 11, 15 ]; n = len(arr); print(getMinSum(arr, n)) # This code is contributed by Ryuga
C#
// C# implementation of the approach using System; class GFG { static int MAX = 25; // Function to return the minimized sum static int getMinSum(int[] arr, int n) { int[] bits_count = new int[MAX]; int max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (int d = 0; d < n; d++) { int e = arr[d], f = 0; while (e > 0) { int rem = e % 2; e = e / 2; if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.Max(max_bit, f); } // Finding element X for (int d = 0; d < max_bit; d++) { int temp = (int)Math.Pow(2, d); if (bits_count[d] > n / 2) ans = ans + temp; } // Taking XOR of elements and finding sum for (int d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code public static void Main(String[] args) { int[] arr = { 3, 5, 7, 11, 15 }; int n = arr.Length; Console.WriteLine(getMinSum(arr, n)); } } /* This code contributed by PrinciRaj1992 */
Javascript
<script> // Javascript implementation of the approach const MAX = 25; // Function to return the minimized sum function getMinSum(arr, n) { let bits_count = new Array(MAX).fill(0), max_bit = 0, sum = 0, ans = 0; // To store the frequency // of bit in every element for (let d = 0; d < n; d++) { let e = arr[d], f = 0; while (e > 0) { let rem = e % 2; e = parseInt(e / 2); if (rem == 1) { bits_count[f] += rem; } f++; } max_bit = Math.max(max_bit, f); } // Finding element X for (let d = 0; d < max_bit; d++) { let temp = Math.pow(2, d); if (bits_count[d] > parseInt(n / 2)) ans = ans + temp; } // Taking XOR of elements and finding sum for (let d = 0; d < n; d++) { arr[d] = arr[d] ^ ans; sum = sum + arr[d]; } return sum; } // Driver code let arr = [ 3, 5, 7, 11, 15 ]; let n = arr.length; document.write(getMinSum(arr, n)); </script>
26
Complejidad de tiempo: O(N*log(max_element)), ya que estamos usando bucles anidados, el bucle exterior atraviesa N veces y el bucle interior atraviesa log(max_element) veces. En el recorrido del bucle interno, estamos disminuyendo por división de piso de 2 en cada recorrido equivalente a 1+1/2+1/4+….1/2 max_element . Donde N es el número de elementos en la array y max_element es el elemento máximo presente en la array.
Espacio auxiliar: O(1), ya que no estamos utilizando ningún espacio adicional.
Publicación traducida automáticamente
Artículo escrito por everythingispossible y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA