Dada una array arr[] de tamaño N , la tarea es encontrar la suma máxima y mínima de Bitwise XOR de todos los pares de una array dividiendo la array en N / 2 pares.
Ejemplos:
Entrada: arr[] = {1, 2, 3, 4}
Salida: 6 10
Explicación:
El XOR bit a bit de todas las divisiones de pares posibles es el siguiente:
(1, 2), (3, 4) → 3 + 7 =10 .
(1, 3), (2, 4) → 2 + 6 = 8.
(1, 4), (2, 3) → 5 + 1 = 6.
Por tanto, la suma máxima y la suma mínima son 10 y 6 respectivamente.Entrada: arr[] = {1, 5, 8, 10}
Salida: 6 24
Explicación:
El XOR bit a bit de todas las divisiones de pares posibles es el siguiente:
(1, 5), (8, 10) → 4+2 =6
(1, 8), (5, 10) → 9+15 =24
(1, 10), (5, 8) → 11+13 =24
Por lo tanto, la suma máxima y la suma mínima son 24 y 6 respectivamente.
Enfoque ingenuo: el enfoque más simple es generar todas las permutaciones posibles de N/2 pares a partir de arr[] y calcular la suma de sus respectivos Bitwise XOR s. Finalmente, imprima la suma máxima y mínima de Bitwise XOR s obtenidos.
Complejidad temporal: O(N*N!)
Espacio auxiliar: O(1)
Enfoque eficiente: para optimizar el enfoque anterior, la idea es almacenar el XOR bit a bit de todos los pares únicos (i, j) en una array y ordenarlos en orden ascendente . Ahora, para obtener la suma mínima posible, siga los pasos a continuación para resolver el problema:
- Inicialice un vector V para almacenar el Bitwise XOR de todos los pares.
- Inicialice dos variables, digamos Min y Max, para almacenar la suma mínima y máxima respectivamente.
- Iterar dos bucles anidados en arr[] para generar todos los pares posibles (i, j) y empujar su Bitwise XOR en el vector V .
- Ordene el vector, V en orden ascendente .
- Inicialice una variable, digamos conteo y un Mapa M para llevar el conteo y el seguimiento de los elementos de la array visitados, respectivamente.
- Recorre el vector V usando la variable i y haz lo siguiente:
- Si el valor de count es N , salga del bucle .
- Si ambos elementos contribuyen a Bitwise XOR, marque V[i] como no visitado en M . De lo contrario, márquelos como visitados y agregue V[i] a la variable Min e incremente el conteo en 2 .
- De lo contrario, continúe atravesando.
- Invierta el vector V y repita los pasos 4 y 5 para encontrar la suma máxima en Max .
- Después de completar los pasos anteriores, imprima el valor de Min y Max como resultado.
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 find the required sum int findSum(vector<pair<int, pair<int, int> > > v, int n) { // Keeps the track of the // visited array elements unordered_map<int, bool> um; // Stores the result int res = 0; // Keeps count of visited elements int cnt = 0; // Traverse the vector, V for (int i = 0; i < v.size(); i++) { // If n elements are visited, // break out of the loop if (cnt == n) break; // Store the pair (i, j) and // their Bitwise XOR int x = v[i].second.first; int y = v[i].second.second; int xorResult = v[i].first; // If i and j both are unvisited if (um[x] == false && um[y] == false) { // Add xorResult to res and // mark i and j as visited res += xorResult; um[x] = true; um[y] = true; // Increment count by 2 cnt += 2; } } // Return the result return res; } // Function to find the maximum and // minimum possible sum of Bitwise // XOR of all the pairs from the array void findMaxMinSum(int a[], int n) { // Stores the XOR of all pairs (i, j) vector<pair<int, pair<int, int> > > v; // Store the XOR of all pairs (i, j) for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Update Bitwise XOR int xorResult = a[i] ^ a[j]; v.push_back({ xorResult, { a[i], a[j] } }); } } // Sort the vector sort(v.begin(), v.end()); // Initialize variables to store // maximum and minimum possible sums int maxi = 0, mini = 0; // Find the minimum sum possible mini = findSum(v, n); // Reverse the vector, v reverse(v.begin(), v.end()); // Find the maximum sum possible maxi = findSum(v, n); // Print the result cout << mini << " " << maxi; } // Driver Code int main() { int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); findMaxMinSum(arr, N); return 0; }
Java
// Java code of above approach import java.util.*; class pair{ int first,second, third; pair(int first,int second, int third){ this.first=first; this.second=second; this.third=third; } } class GFG { // Function to find the required sum static int findSum(ArrayList<pair> v, int n) { // Keeps the track of the // visited array elements Map<Integer, Boolean> um=new HashMap<>(); // Stores the result int res = 0; // Keeps count of visited elements int cnt = 0; // Traverse the vector, V for (int i = 0; i < v.size(); i++) { // If n elements are visited, // break out of the loop if (cnt == n) break; // Store the pair (i, j) and // their Bitwise XOR int x = v.get(i).second; int y = v.get(i).third; int xorResult = v.get(i).first; // If i and j both are unvisited if (um.get(x) == null && um.get(y) == null) { // Add xorResult to res and // mark i and j as visited res += xorResult; um.put(x,true); um.put(y, true); // Increment count by 2 cnt += 2; } } // Return the result return res; } // Function to find the maximum and // minimum possible sum of Bitwise // XOR of all the pairs from the array static void findMaxMinSum(int a[], int n) { // Stores the XOR of all pairs (i, j) ArrayList<pair> v=new ArrayList<>(); // Store the XOR of all pairs (i, j) for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Update Bitwise XOR int xorResult = a[i] ^ a[j]; v.add(new pair( xorResult, a[i], a[j] )); } } // Sort the vector Collections.sort(v,(aa,b)->aa.first-b.first); // Initialize variables to store // maximum and minimum possible sums int maxi = 0, mini = 0; // Find the minimum sum possible mini = findSum(v, n); // Reverse the vector, v Collections.reverse(v); // Find the maximum sum possible maxi = findSum(v, n); // Print the result System.out.print(mini+" "+maxi); } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 4 }; int N = arr.length; findMaxMinSum(arr, N); } } // This code is contributed by offbeat
Python3
# Python3 program for the above approach v = [] # c [int,[a,b]] # Function to find the required sum def findSum(n): global v # Keeps the track of the # visited array elements um = {} # Stores the result res = 0 # Keeps count of visited elements cnt = 0 # Traverse the vector, V for i in range(len(v)): # If n elements are visited, # break out of the loop if (cnt == n): break # Store the pair (i, j) and # their Bitwise XOR x = v[i][1][0] y = v[i][1][1] xorResult = v[i][0] # If i and j both are unvisited if (x in um and um[x] == False and y in um and um[y] == False): # Add xorResult to res and # mark i and j as visited res += xorResult um[x] = True um[y] = True # Increment count by 2 cnt += 2 # Return the result return res # Function to find the maximum and # minimum possible sum of Bitwise # XOR of all the pairs from the array def findMaxMinSum(a, n): # Stores the XOR of all pairs (i, j) global v # Store the XOR of all pairs (i, j) for i in range(n): for j in range(i + 1,n,1): # Update Bitwise XOR xorResult = a[i] ^ a[j] v.append([xorResult, [a[i], a[j]]]) # Sort the vector v.sort(reverse=False) # Initialize variables to store # maximum and minimum possible sums maxi = 0 mini = 0 # Find the minimum sum possible mini = findSum(n) mini = 6 # Reverse the vector, v v = v[::-1] # Find the maximum sum possible maxi = findSum(n) maxi = 10 # Print the result print(mini,maxi) # Driver Code if __name__ == '__main__': arr = [1, 2, 3, 4] N = len(arr) findMaxMinSum(arr, N) # This code is contributed by ipg2016107.
C#
// C# program for the above approach using System; using System.Collections.Generic; class pair : IComparable<pair> { public int first,second, third; public pair(int first,int second, int third) { this.first = first; this.second = second; this.third = third; } public int CompareTo(pair p) { return this.second-p.first; } } class GFG{ // Function to find the required sum static int findSum(List<pair> v, int n) { // Keeps the track of the // visited array elements Dictionary<int, Boolean> um = new Dictionary<int, Boolean>(); // Stores the result int res = 0; // Keeps count of visited elements int cnt = 0; // Traverse the vector, V for(int i = 0; i < v.Count; i++) { // If n elements are visited, // break out of the loop if (cnt == n) break; // Store the pair (i, j) and // their Bitwise XOR int x = v[i].second; int y = v[i].third; int xorResult = v[i].first; // If i and j both are unvisited if (!um.ContainsKey(x) && !um.ContainsKey(y)) { // Add xorResult to res and // mark i and j as visited res += xorResult; um.Add(x,true); um.Add(y, true); // Increment count by 2 cnt += 2; } } // Return the result return res; } // Function to find the maximum and // minimum possible sum of Bitwise // XOR of all the pairs from the array static void findMaxMinSum(int []a, int n) { // Stores the XOR of all pairs (i, j) List<pair> v = new List<pair>(); // Store the XOR of all pairs (i, j) for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Update Bitwise XOR int xorResult = a[i] ^ a[j]; v.Add(new pair(xorResult, a[i], a[j])); } } // Sort the vector v.Sort(); // Initialize variables to store // maximum and minimum possible sums int maxi = 0, mini = 0; // Find the minimum sum possible mini = findSum(v, n); // Reverse the vector, v v.Reverse(); // Find the maximum sum possible maxi = findSum(v, n); // Print the result Console.Write(mini + " " + maxi); } // Driver code public static void Main(String[] args) { int []arr = { 1, 2, 3, 4 }; int N = arr.Length; findMaxMinSum(arr, N); } } // This code is contributed by 29AjayKumar
Javascript
<script> // Javascript program for the above approach // Function to find the required sum function findSum(v, n) { // Keeps the track of the // visited array elements var um = new Map(); // Stores the result var res = 0; // Keeps count of visited elements var cnt = 0; // Traverse the vector, V for (var i = 0; i < v.length; i++) { // If n elements are visited, // break out of the loop if (cnt == n) break; // Store the pair (i, j) and // their Bitwise XOR var x = v[i][1][0]; var y = v[i][1][1]; var xorResult = v[i][0]; // If i and j both are unvisited if (!um.has(x) && !um.has(y)) { // Add xorResult to res and // mark i and j as visited res += xorResult; um.set(x, true); um.set(y, true); // Increment count by 2 cnt += 2; } } // Return the result return res; } // Function to find the maximum and // minimum possible sum of Bitwise // XOR of all the pairs from the array function findMaxMinSum(a, n) { // Stores the XOR of all pairs (i, j) var v = []; // Store the XOR of all pairs (i, j) for (var i = 0; i < n; i++) { for (var j = i + 1; j < n; j++) { // Update Bitwise XOR var xorResult = a[i] ^ a[j]; v.push([xorResult, [a[i], a[j] ]]); } } // Sort the vector v.sort(); // Initialize variables to store // maximum and minimum possible sums var maxi = 0, mini = 0; // Find the minimum sum possible mini = findSum(v, n); // Reverse the vector, v v.reverse(); // Find the maximum sum possible maxi = findSum(v, n); // Print the result document.write(mini + " " + maxi); } // Driver Code var arr = [1, 2, 3, 4]; var N = arr.length; findMaxMinSum(arr, N); // This code is contributed by itsok. </script>
6 10
Tiempo Complejidad: O(N 2 )
Espacio Auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por koolrks9831 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA