📌  相关文章
📜  计算给定范围内矩阵的行和列总和的查询

📅  最后修改于: 2021-09-03 03:23:53             🧑  作者: Mango

给定一个大小为N * M的矩阵A[][]和一个由{L, R}形式的Q 个查询组成的二维数组queries[][] ,任务是计算行总和和列总和的数量它们是[L, R]范围内的整数。

例子:

高效的方法:思想是逐行和逐列遍历矩阵,并分别预先计算每行和每列的总和。遍历数组查询 [][]并使用二分搜索计算给定范围中存在的行总和或列总和的数量。请按照以下步骤解决问题:

  1. 初始化两个辅助数组,比如row_sum[]col_sum[] ,以存储行和列的总和。
  2. 初始化另一个数组,例如sum_list[],以存储组合的所有行总和和列总和元素。
  3. 按升序对数组sum_list[]进行排序。
  4. 遍历数组查询 []和每个查询:
    • 执行二分搜索以找到最左边和,即L的索引,比如i
    • 再次,执行二分查找找到最右边和的索引j ,即R
    • 打印j – i + 1作为查询的结果。

下面是上述方法的实现:

Java
// Java program for the above approach
 
import java.io.*;
import java.util.*;
class GFG {
 
    // Function to preprocess the matrix to execute the
    // queries
    static void totalCount(int[][] A, int N,
                           int M, int[][] queries, int Q)
    {
        // Stores the sum of each row
        int row_sum[] = new int[N];
 
        // Stores the sum of each col
        int col_sum[] = new int[M];
 
        // Traverse the matrix and calculate
        // sum of each row and column
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
 
                row_sum[i] += A[i][j];
                col_sum[j] += A[i][j];
            }
        }
 
        ArrayList sum_list
            = new ArrayList<>();
 
        // Insert all row sums in sum_list
        for (int i = 0; i < N; i++)
            sum_list.add(row_sum[i]);
 
        // Insert all column sums in sum_list
        for (int i = 0; i < M; i++)
            sum_list.add(col_sum[i]);
 
        // Sort the array in ascending order
        Collections.sort(sum_list);
 
        // Traverse the array queries[][]
        for (int i = 0; i < Q; i++) {
            int L = queries[i][0];
            int R = queries[i][1];
 
            // Search the leftmost index of L
            int l = left_search(sum_list, L);
 
            // Search the rightmost index of R
            int r = right_search(sum_list, R);
 
            System.out.print(r - l + 1 + " ");
        }
    }
 
    // Function to search for the
    // leftmost index of given number
    static int left_search(
        ArrayList A,
        int num)
    {
        // Initialize low, high and ans
        int low = 0, high = A.size() - 1;
        int ans = 0;
 
        while (low <= high) {
 
            // Stores mid
            int mid = low + (high - low) / 2;
 
            // If A[mid] >= num
            if (A.get(mid) >= num) {
 
                ans = mid;
                high = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
        return ans;
    }
 
    // Function to search for the
    // rightmost index of given number
    static int right_search(
        ArrayList A,
        int num)
    {
        // Intialise low, high and ans
        int low = 0, high = A.size() - 1;
        int ans = high;
 
        while (low <= high) {
 
            // Stores mid
            int mid = low + (high - low) / 2;
 
            // If A[mid] <= num
            if (A.get(mid) <= num) {
 
                // Update ans
                ans = mid;
 
                // Update mid
                low = mid + 1;
            }
            else {
 
                // Update high
                high = mid - 1;
            }
        }
 
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given dimensions of matrix
        int N = 3, M = 2;
 
        // Given matrix
        int A[][] = { { 13, 3 },
                      { 9, 4 },
                      { 6, 10 } };
 
        // Given number of queries
        int Q = 2;
 
        // Given queries
        int queries[][] = { { 10, 20 }, { 25, 35 } };
 
        // Function call to count the
        // number row-sums and column-sums
        // present in the given ranges
        totalCount(A, N, M, queries, Q);
    }
}


Python3
# Python3 program for the above approach
from collections import deque
from bisect import bisect_left, bisect_right
 
# Function to preprocess the matrix to execute the
# queries
def totalCount(A, N, M, queries, Q):
     
    # Stores the sum of each row
    row_sum = [0]*N
 
    # Stores the sum of each col
    col_sum = [0]*M
 
    # Traverse the matrix and calculate
    # sum of each row and column
    for i in range(N):
        for j in range(M):
            row_sum[i] += A[i][j]
            col_sum[j] += A[i][j]
 
    sum_list = []
 
    # Insert all row sums in sum_list
    for i in range(N):
        sum_list.append(row_sum[i])
 
    # Insert all column sums in sum_list
    for i in range(M):
        sum_list.append(col_sum[i])
 
    # Sort the array in ascending order
    sum_list = sorted(sum_list)
 
    # Traverse the array queries[][]
    for i in range(Q):
        L = queries[i][0]
        R = queries[i][1]
 
        # Search the leftmost index of L
        l = left_search(sum_list, L)
 
        # Search the rightmost index of R
        r = right_search(sum_list, R)
        print(r - l + 1, end = " ")
 
# Function to search for the
# leftmost index of given number
def left_search(A, num):
   
    # Initialize low, high and ans
    low, high = 0, len(A) - 1
    ans = 0
    while (low <= high):
 
        # Stores mid
        mid = low + (high - low) // 2
 
        # If A[mid] >= num
        if (A[mid] >= num):
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    return ans
 
# Function to search for the
# rightmost index of given number
def right_search(A, num):
   
    # Intialise low, high and ans
    low, high = 0, len(A) - 1
    ans = high
    while (low <= high):
 
        # Stores mid
        mid = low + (high - low) // 2
 
        # If A[mid] <= num
        if (A[mid] <= num):
            # Update ans
            ans = mid
 
            # Update mid
            low = mid + 1
        else:
 
            # Update high
            high = mid - 1
 
    return ans
 
# Driver Code
if __name__ == '__main__':
   
    # Given dimensions of matrix
    N, M = 3, 2
 
    # Given matrix
    A = [ [ 13, 3 ],
          [ 9, 4 ],
          [ 6, 10 ] ]
 
    # Given number of queries
    Q = 2
 
    # Given queries
    queries= [ [ 10, 20 ], [ 25, 35 ] ]
 
    # Function call to count the
    # number row-sums and column-sums
    # present in the given ranges
    totalCount(A, N, M, queries, Q)
 
# This code is contributed by mohit kumar 29.


C#
using System;
using System.Collections.Generic;
class GFG
{
     
    // Function to preprocess the matrix to execute the
    // queries
    static void totalCount(int[,] A, int N, int M,
                           int[,] queries, int Q)
    {
       
        // Stores the sum of each row
        int []row_sum = new int[N];
 
        // Stores the sum of each col
        int []col_sum = new int[M];
 
        // Traverse the matrix and calculate
        // sum of each row and column
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
 
                row_sum[i] += A[i,j];
                col_sum[j] += A[i,j];
            }
        }
 
        List sum_list = new List();
         
        // Insert all row sums in sum_list
        for (int i = 0; i < N; i++)
            sum_list.Add(row_sum[i]);
 
        // Insert all column sums in sum_list
        for (int i = 0; i < M; i++)
            sum_list.Add(col_sum[i]);
 
        // Sort the array in ascending order
        sum_list.Sort();
 
        // Traverse the array queries[][]
        for (int i = 0; i < Q; i++) {
            int L = queries[i,0];
            int R = queries[i,1];
 
            // Search the leftmost index of L
            int l = left_search(sum_list, L);
 
            // Search the rightmost index of R
            int r = right_search(sum_list, R);
 
           Console.Write(r - l + 1 + " ");
        }
    }
 
    // Function to search for the
    // leftmost index of given number
    static int left_search(List A, int num)
    {
       
        // Initialize low, high and ans
        int low = 0, high = A.Count- 1;
        int ans = 0;
        while (low <= high)
        {
 
            // Stores mid
            int mid = low + (high - low) / 2;
 
            // If A[mid] >= num
            if (A[mid] >= num) {
 
                ans = mid;
                high = mid - 1;
            }
            else {
                low = mid + 1;
            }
        }
        return ans;
    }
 
    // Function to search for the
    // rightmost index of given number
    static int right_search( List A,int num)
    {
        // Intialise low, high and ans
        int low = 0, high = A.Count- 1;
        int ans = high;
 
        while (low <= high) {
 
            // Stores mid
            int mid = low + (high - low) / 2;
 
            // If A[mid] <= num
            if (A[mid] <= num) {
 
                // Update ans
                ans = mid;
 
                // Update mid
                low = mid + 1;
            }
            else {
 
                // Update high
                high = mid - 1;
            }
        }
 
        return ans;
    }
     
//driver code
static void Main()
{
       int N = 3, M = 2;
 
        // Given matrix
        int [,]A = new int[,]{ { 13, 3 },{ 9, 4 },{ 6, 10 } };
 
        // Given number of queries
        int Q = 2;
 
        // Given queries
        int [,]queries = new int[,]{ { 10, 20 }, { 25, 35 } };
 
        // Function call to count the
        // number row-sums and column-sums
        // present in the given ranges
        totalCount(A, N, M, queries, Q);
    }
}
 
//This code is contributed by SoumikMondal


输出:
4 1

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live