Suma máxima de Bitwise XOR de elementos con sus respectivas posiciones en una permutación de tamaño N

Dado un entero positivo N , la tarea para cualquier permutación de tamaño N que tenga elementos en el rango [0, N – 1] , es calcular la suma de Bitwise XOR de todos los elementos con su posición respectiva.

Por ejemplo: para la permutación {3, 4, 2, 1, 0}, sum = (0^3 + 1^4 + 2^2 + 3^1 + 4^0) = 2 .

Ejemplos:

Entrada: N = 3
Salida: 6
Explicación: Para las permutaciones {1, 2, 0} y {2, 0, 1} , la suma es 6 .

Entrada: N = 2
Salida: 2

Planteamiento: Para resolver este problema, la idea es recurrir a la recursividad para generar todas las permutaciones posibles de los enteros [0, N – 1] y calcular la puntuación de cada uno de ellos y luego encontrar la puntuación máxima entre todas las permutaciones formadas.

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 calculate the score
int calcScr(vector<int>arr){
 
  // Stores the possible score for
  // the current permutation
  int ans = 0;
 
  // Traverse the permutation array
  for(int i = 0; i < arr.size(); i++)
    ans += (i ^ arr[i]);
 
  // Return the final score
  return ans;
}
 
// Function to generate all the possible
// permutation and get the max score
int getMax(vector<int> arr, int ans, vector<bool> chosen, int N)
{
 
  // If arr[] length is equal to N
  // process the permutation
  if (arr.size() == N){
    ans = max(ans, calcScr(arr));
    return ans;
 
  }
 
  // Generating the permutations
  for (int i = 0; i < N; i++)
  {
 
    // If the current element is
    // chosen
    if(chosen[i])
      continue;
 
    // Mark the current element
    // as true
    chosen[i] = true;
    arr.push_back(i);
 
    // Recursively call for next
    // possible permutation
    ans = getMax(arr, ans, chosen, N);
 
    // Backtracking
    chosen[i] = false;
    arr.pop_back();
  }
 
  // Return the ans
  return ans;
}
 
// Driver Code
int main()
{
 
  int N = 2;
 
  // Stores the permutation
  vector<int> arr;
 
  // To display the result
  int ans = -1;
  vector<bool>chosen(N,false);
  ans = getMax(arr, ans, chosen, N);
 
  cout << ans << endl;
}
 
// This code is contributed by bgangwar59.

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
// Function to calculate the score
static int calcScr(ArrayList<Integer>arr)
{
 
  // Stores the possible score for
  // the current permutation
  int ans = 0;
 
  // Traverse the permutation array
  for(int i = 0; i < arr.size(); i++)
    ans += (i ^ arr.get(i));
 
  // Return the final score
  return ans;
}
 
// Function to generate all the possible
// permutation and get the max score
static int getMax(ArrayList<Integer> arr, int ans, ArrayList<Boolean> chosen, int N)
{
 
  // If arr[] length is equal to N
  // process the permutation
  if (arr.size() == N)
  {
    ans = Math.max(ans, calcScr(arr));
    return ans;
 
  }
 
  // Generating the permutations
  for (int i = 0; i < N; i++)
  {
 
    // If the current element is
    // chosen
    if(chosen.get(i))
      continue;
 
    // Mark the current element
    // as true
    chosen.set(i, true);
    arr.add(i);
 
    // Recursively call for next
    // possible permutation
    ans = getMax(arr, ans, chosen, N);
 
    // Backtracking
    chosen.set(i, false);
    arr.remove(arr.size()-1);
  }
 
  // Return the ans
  return ans;
}
 
// Driver Code
public static void main(String[] args)
{
 
  int N = 2;
 
  // Stores the permutation
  ArrayList<Integer> arr = new ArrayList<Integer>();
 
  // To display the result
  int ans = -1;
  ArrayList<Boolean> chosen = new ArrayList<Boolean>(Collections.nCopies(N, false));
  ans = getMax(arr, ans, chosen, N);
 
  System.out.print(ans +"\n");
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python program for the above approach
 
# Function to generate all the possible
# permutation and get the max score
def getMax(arr, ans, chosen, N):
 
    # If arr[] length is equal to N
    # process the permutation
    if len(arr) == N:
        ans = max(ans, calcScr(arr))
        return ans
 
    # Generating the permutations
    for i in range(N):
       
        # If the current element is
        # chosen
        if chosen[i]:
            continue
             
        # Mark the current element
        # as true
        chosen[i] = True
        arr.append(i)
         
        # Recursively call for next
        # possible permutation
        ans = getMax(arr, ans, chosen, N)
         
        # Backtracking
        chosen[i] = False
        arr.pop()
         
    # Return the ans
    return ans
 
# Function to calculate the score
def calcScr(arr):
     
    # Stores the possible score for
    # the current permutation
    ans = 0
     
    # Traverse the permutation array
    for i in range(len(arr)):
        ans += (i ^ arr[i])
         
    # Return the final score
    return ans
 
 
# Driver Code
N = 2
 
# Stores the permutation
arr = []
 
# To display the result
ans = -1
 
chosen = [False for i in range(N)]
 
ans = getMax(arr, ans, chosen, N)
 
print(ans)

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to calculate the score
  static int calcScr(List<int>arr)
  {
 
    // Stores the possible score for
    // the current permutation
    int ans = 0;
 
    // Traverse the permutation array
    for(int i = 0; i < arr.Count; i++)
      ans += (i ^ arr[i]);
 
    // Return the readonly score
    return ans;
  }
 
  // Function to generate all the possible
  // permutation and get the max score
  static int getMax(List<int> arr, int ans, List<Boolean> chosen, int N)
  {
 
    // If []arr length is equal to N
    // process the permutation
    if (arr.Count == N)
    {
      ans = Math.Max(ans, calcScr(arr));
      return ans;
 
    }
 
    // Generating the permutations
    for (int i = 0; i < N; i++)
    {
 
      // If the current element is
      // chosen
      if(chosen[i])
        continue;
 
      // Mark the current element
      // as true
      chosen[i] = true;
      arr.Add(i);
 
      // Recursively call for next
      // possible permutation
      ans = getMax(arr, ans, chosen, N);
 
      // Backtracking
      chosen[i] = false;
      arr.Remove(arr.Count-1);
    }
 
    // Return the ans
    return ans;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
 
    int N = 2;
 
    // Stores the permutation
    List<int> arr = new List<int>();
 
    // To display the result
    int ans = -1;
    List<bool> chosen = new List<bool>(N);
    for(int i = 0; i < N; i++)
      chosen.Add(false);
    ans = getMax(arr, ans, chosen, N);
 
    Console.Write(ans +"\n");
  }
}
 
// This code is contributed by shikhasingrajput

Javascript

<script>
 
// JavaScript program for the above approach
 
 
// Function to calculate the score
function calcScr(arr) {
 
    // Stores the possible score for
    // the current permutation
    let ans = 0;
 
    // Traverse the permutation array
    for (let i = 0; i < arr.length; i++)
        ans += (i ^ arr[i]);
 
    // Return the final score
    return ans;
}
 
// Function to generate all the possible
// permutation and get the max score
function getMax(arr, ans, chosen, N) {
 
    // If arr[] length is equal to N
    // process the permutation
    if (arr.length == N) {
        ans = Math.max(ans, calcScr(arr));
        return ans;
 
    }
 
    // Generating the permutations
    for (let i = 0; i < N; i++) {
 
        // If the current element is
        // chosen
        if (chosen[i])
            continue;
 
        // Mark the current element
        // as true
        chosen[i] = true;
        arr.push(i);
 
        // Recursively call for next
        // possible permutation
        ans = getMax(arr, ans, chosen, N);
 
        // Backtracking
        chosen[i] = false;
        arr.pop();
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
 
 
let N = 2;
 
// Stores the permutation
let arr = [];
 
// To display the result
let ans = -1;
let chosen = new Array(N).fill(false);
ans = getMax(arr, ans, chosen, N);
 
document.write(ans + "<br>");
 
 
// This code is contributed by gfgking
 
</script>
Producción: 

2

 

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

Publicación traducida automáticamente

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