Saturday, 16 Oct 2021

# Minimize sum of an array having Bitwise AND of all its pairs present in a given matrix

Minimize sum of an array having Bitwise AND of all its pairs present in a given matrixGiven a square symmetric matrix mat[][] of size N, the task is to find the minimum sum possible of an array arr[] of size N, such that for i != j, the value of Bitwise AND of arr[i] and arr[j] is mat[i][j].Examples:Input: mat[][] = {{-1, 0, 1, 1, 1}, {0, -1, 2, 0, 2}, {1, 2, -1, 1, 3}, {1, 0, 1, -1, -1}, {1, 2, 3, 1, -1}}Output: 10Explanation:The array that satisfy the above criteria is {1, 2, 3, 1, 3}.The sum of array elements is 1 + 2 + 3 + 1 + 3 = 10, which is minimum.Input: mat[][] = {{-1, 2, 3}, {2, -1, 7}, {3, 7, -1}}Output: 17Approach: The given problem can be solved based on the following observations: The binary representation of the Bitwise AND of two numbers have only those bit set that is set in both the numbers.So from the property of Bitwise AND it can be observed that a number in the resultant array must have all the bit set that is set in at least one of the matrix elements in the ith row.Therefore, the number at ith position in the resultant array is Bitwise OR of all the elements of the matrix at the ith row.Follow the steps below to solve the problem:Initialize a variable say sum to 0 that stores the minimum possible sum of the array.Iterate over the range [0, N – 1] and add the value of Bitwise OR of all the elements of the matrix at the ith row except mat[i][i] to the variable sum.After completing the above steps, print the value of the sum as the resultant possible sum.Below is the implementation of the above approach:C++  #include using namespace std;  int findMinSum(vector mat,               int N){        int sum = 0;          for (int i = 0; i < N; i++) {                          int res = 0;                  for (int j = 0; j < N; j++) {                          if (i != j) {                                                  res |= mat[i][j];            }        }                  sum += res;    }          return sum;}  int main(){    vector mat        = { { -1, 2, 3 }, { 9, -1, 7 }, { 4, 5, -1 } };    int N = mat.size();    cout