📜  最小子矩阵,XOR最大为Xth

📅  最后修改于: 2021-05-06 03:16:03             🧑  作者: Mango

给定尺寸为N×M的矩阵m [] []和整数K ,计算XOR(i,j)等于从索引(1,1)到(i,j)的子矩阵所有元素的按位Xor。 ) ,用于矩阵的每个索引。任务是找到具有K最大XOR(i,j)值的子矩阵{(1,1),…,(i,j)} 。如果存在多个这样的子矩阵,则打印最小的子矩阵。

注意:考虑矩阵从(1,1)开始的索引。

例子:

方法:想法是使用动态编程找到XOR(i,j)。

  • 按xor [i] [j] = xor [i-1] [j] ^ xor [i] [j-1] ^ xor [i-1] [j-1] ^计算按位XOR(i,j) m [i] [j]。
  • 将针对各个索引(i,j)获得的XOR(i,j)值存储在Map中。
  • 使用大小为K的最小堆找到所有XOR(i,j)值的K最大值。
  • 使用Map找到XOR(i,j)等于在上述步骤中获得的第K最大值的最小索引(i,j)

下面是上述方法的实现:

C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to print smallest index of
// Kth maximum xors value of submatrices
void smallestPosition(int m[][3], int k, int row)
{
     
    // Dimensions of matrix
    int n = row;
    int mm = row;
 
    // Stores xors values for every index
    int xors[n][mm];
 
    // Min heap to find the
    // kth maximum xors value
    priority_queue,
           greater> minHeap;
 
    // Stores indices for
    // corresponding xors vlaues
    map> map;
 
    // Traversing matrix to
    // calculate xors values
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < mm; j++)
        {
            int a = i - 1 >= 0 ? xors[i - 1][j] : 0;
            int b = j - 1 >= 0 ? xors[i][j - 1] : 0;
            int c = (i - 1 >= 0 && j - 1 >= 0) ?
                xors[i - 1][j - 1] : 0;
 
            xors[i][j] = m[i][j] ^ a ^ b ^ c;
 
            // Insert calculated value
            // in Min Heap
            minHeap.push(xors[i][j]);
 
            // If size exceeds k
            if (minHeap.size() > k)
            {
                 
                // Remove the minimum
                minHeap.pop();
            }
 
            // Store smallest index
            // containing xors[i][j]
            if (map.find(xors[i][j]) == map.end())
                map[xors[i][j]] = {i, j};
        }
    }
     
    // Stores the kth maximum element
    int kth_max_e = minHeap.top();
 
    // Print the required index
    cout << (map[kth_max_e][0] + 1) << " "
         << (map[kth_max_e][1] + 1);
}
 
// Driver Code
int main()
{
    int m[][3] = { { 1, 2, 3 },
                   { 2, 2, 1 },
                   { 2, 4, 2 } };
    int k = 1;
 
    // Function call
    smallestPosition(m, k, 3);
}
 
// This code is contributed by grand_master


Java
// Java Program for above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to print smallest index of
    // Kth maximum Xor value of submatrices
    static void smallestPosition(int m[][], int k)
    {
 
        // Dimensions of matrix
        int n = m.length;
        int mm = m[0].length;
 
        // Stores XOR values for every index
        int[][] xor = new int[n][mm];
 
        // Min heap to find the
        // kth maximum XOR value
        PriorityQueue minHeap
            = new PriorityQueue<>();
 
        // Stores indices for
        // corresponding XOR vlaues
        Map map
            = new HashMap<>();
 
        // Traversing matrix to
        // calculate XOR values
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < mm; j++) {
 
                int a = i - 1 >= 0
                            ? xor[i - 1][j]
                            : 0;
 
                int b = j - 1 >= 0
                            ? xor[i][j - 1]
                            : 0;
 
                int c = (i - 1 >= 0 && j - 1 >= 0)
                            ? xor[i - 1][j - 1]
                            : 0;
 
                xor[i][j] = m[i][j] ^ a ^ b ^ c;
 
                // Insert calculated value
                // in Min Heap
                minHeap.add(xor[i][j]);
 
                // If size exceeds k
                if (minHeap.size() > k) {
 
                    // Remove the minimum
                    minHeap.poll();
                }
 
                // Store smallest index
                // containing xor[i][j]
                if (!map.containsKey(xor[i][j]))
                    map.put(xor[i][j],
                            new int[] { i, j });
            }
        }
 
        // Stores the kth maximum element
        int kth_max_e = minHeap.poll();
 
        // Print the required index
        System.out.println(
            (map.get(kth_max_e)[0] + 1)
            + " " + (map.get(kth_max_e)[1] + 1));
    }
    // Driver Code
    public static void main(String[] args)
    {
 
        int m[][] = { { 1, 2, 3 },
                      { 2, 2, 1 },
                      { 2, 4, 2 } };
        int k = 1;
 
        // Function call
        smallestPosition(m, k);
    }
}


Python3
# Python3 Program for the
# above approach
 
# Function to print smallest index of
# Kth maximum Xor value of submatrices
def smallestPosition(m, k) :
 
    # Dimensions of matrix
    n = len(m)
    mm = len(m[1])
     
    # Stores XOR values for
    # every index
    xor = [[0 for i in range(mm)] for j in range(n)]
     
    # Min heap to find the
    # kth maximum XOR value
    minHeap = []
     
    # Stores indices for
    # corresponding XOR vlaues
    Map = {}
     
    # Traversing matrix to
    # calculate XOR values
    for i in range(n) :
        for j in range(mm) :
            if i - 1 >= 0 :
                a = xor[i - 1][j]
            else :
                a = 0
                 
            if j - 1 >= 0 :
                b = xor[i][j - 1]
            else :
                b = 0
                 
            if i - 1 >= 0 and j - 1 >= 0 :
                c = xor[i - 1][j - 1]
            else :
                c = 0
                 
            xor[i][j] = m[i][j] ^ a ^ b ^ c
             
            # Insert calculated value
            # in Min Heap
            minHeap.append(xor[i][j])
            minHeap.sort()
             
            # If size exceeds k
            if (len(minHeap) > k) :
               
                # Remove the minimum
                del minHeap[0]
            # Store smallest index
            # containing xor[i,j]
            if xor[i][j] not in Map :
                Map[xor[i][j]] = [i, j]
     
    minHeap.sort()
     
    # Stores the kth maximum
    # element
    kth_max_e = minHeap[0]
     
    # Print the required index
    print((Map[kth_max_e][0] + 1), (Map[kth_max_e][1] + 1))
 
# Driver code   
m = [[1, 2, 3],
    [2, 2, 1],
    [2, 4, 2]]
k = 1
 
# Function call
smallestPosition(m, k)
 
# This code is contributed by divyesh072019


C#
// C# Program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to print smallest index of
// Kth maximum Xor value of submatrices
static void smallestPosition(int [,]m,
                             int k)   
{
  // Dimensions of matrix
  int n = m.GetLength(0);
  int mm = m.GetLength(1);
 
  // Stores XOR values for
  // every index
  int[,] xor = new int[n, mm];
 
  // Min heap to find the
  // kth maximum XOR value
  List minHeap =
            new List();
 
  // Stores indices for
  // corresponding XOR vlaues
  Dictionary map = new Dictionary();
 
  // Traversing matrix to
  // calculate XOR values
  for (int i = 0; i < n; i++)
  {
    for (int j = 0; j < mm; j++)
    {
      int a = i - 1 >= 0 ?
              xor[i - 1, j] : 0;
      int b = j - 1 >= 0 ?
              xor[i, j - 1] : 0;
      int c = (i - 1 >= 0 &&
               j - 1 >= 0) ?
               xor[i - 1, j - 1] : 0;
      xor[i, j] = m[i, j] ^
                  a ^ b ^ c;
 
      // Insert calculated value
      // in Min Heap
      minHeap.Add(xor[i, j]);
      minHeap.Sort();
       
      // If size exceeds k
      if (minHeap.Count > k)
      {
        // Remove the minimum
        minHeap.RemoveAt(0);
      }
 
      // Store smallest index
      // containing xor[i,j]
      if (!map.ContainsKey(xor[i, j]))
        map.Add(xor[i, j],
                new int[] {i, j});
    }
  }
  minHeap.Sort();
 
  // Stores the kth maximum
  // element
  int kth_max_e = minHeap[0];
 
  // Print the required index
  Console.WriteLine((map[kth_max_e][0] + 1) +
                     " " + (map[kth_max_e][1] + 1));
}
 
// Driver Code
public static void Main(String[] args)
{
  int [,]m = {{1, 2, 3},
              {2, 2, 1},
              {2, 4, 2}};
  int k = 1;
 
  // Function call
  smallestPosition(m, k);
}
}
 
// This code is contributed by Amit Katiyar


输出:
3 2

时间复杂度: O(N * M * log K)
辅助空间: O(N * M)