给定大小为N的数组arr [] ,任务是通过将数组拆分为N / 2对来查找数组中所有对的按位XOR的最大和最小和。
例子:
Input: arr[] = {1, 2, 3, 4}
Output: 6 10
Explanation:
Bitwise XOR of the all possible pair splits are as follows:
(1, 2), (3, 4) → 3 + 7 =10.
(1, 3), (2, 4) → 2 + 6 = 8.
(1, 4), (2, 3) → 5 + 1 = 6.
Therefore, the maximum sum and minimum sums are 10 and 6 respectively.
Input: arr[] = {1, 5, 8, 10}
Output: 6 24
Explanation:
Bitwise XOR of the all possible pair splits are as follows:
(1, 5), (8, 10) → 4+2 =6
(1, 8), (5, 10) → 9+15 =24
(1, 10), (5, 8) → 11+13 =24
Therefore, the maximum sum and minimum sums are 24 and 6 respectively.
天真的方法:最简单的方法是从arr []生成N / 2对的所有可能排列,并计算它们各自按位XOR的总和。最后,打印获得的按位XOR的最大和最小和。
时间复杂度: O(N * N!)
辅助空间: O(1)
高效方法:为了优化上述方法,其思想是将所有唯一对(i,j)的按位XOR存储在数组中,并按升序对其进行排序。现在,要获得最小的总和,请按照以下步骤解决问题:
- 初始化向量V来存储所有对的按位XOR。
- 初始化两个变量,例如Min和Max,分别存储最小和最大和。
- 迭代arr []中的两个嵌套循环以生成所有可能的对(i,j) ,并将其按位XOR推入向量V。
- 将向量V升序排序。
- 初始化一个变量,例如count和Map M,以分别保持计数和跟踪访问的数组元素。
- 使用变量i遍历向量V并执行以下操作:
- 如果count的值为N ,则跳出循环。
- 如果两个元素都对按位XOR起作用,则在M中将V [i]标记为未访问。否则,将其标记为已访问,并将V [i]添加到变量Min中,并以2递增计数。
- 否则,继续运行。
- 反转向量V并重复步骤4和5,以找到Max中的最大和。
- 完成上述步骤后,打印Min和Max的值作为结果。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the required sum
int findSum(vector > > v, int n)
{
// Keeps the track of the
// visited array elements
unordered_map 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 > > 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 v, int n)
{
// Keeps the track of the
// visited array elements
Map 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 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
# Python 3 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.
6 10
时间复杂度: O(N 2 )
辅助空间: O(N)