📜  求矩阵中 M 次运算后 (Xi, Yi) 处的权重

📅  最后修改于: 2022-05-13 01:57:24.873000             🧑  作者: Mango

求矩阵中 M 次运算后 (Xi, Yi) 处的权重

给定笛卡尔平面上的 nxn个点,任务是在m 次运算后找到 (x i , y j ) 处的权重。 x i , y j , w表示在 x = x i和 y = y j线上的所有点上添加权重w的操作。

例子:

天真的方法:
考虑一个二维数组 arr[n][n] = {0} 并执行给定的操作,然后检索(x i , y j )处的权重。这种方法将花费O(n*m)时间。



有效的方法:

  • 考虑数组 arrX[n] = arrY[n] = {0}。
  • 将操作 x i , y j , w 重新定义为
    arrX[i] += w 
    and
    arrY[j] += w
    
  • 使用 (x i , y j ) 求重量
    w = arrX[i] + arrY[j]

    下面是上述方法的实现:

    C++
    // C++ program to find the
    // weight at xi and yi
      
    #include 
    using namespace std;
      
    // Function to calculate weight at (xFind, yFind)
    int findWeight(vector >& operations,
                   int n, int m,
                   int xFind, int yFind)
    {
        int row[n] = { 0 };
        int col[n] = { 0 };
      
        // Loop to perform operations
        for (int i = 0; i < m; i++) {
      
            // Updating row
            row[operations[i][0]]
                += operations[i][2];
      
            // Updating column
            col[operations[i][0]]
                += operations[i][2];
        }
      
        // Find weight at (xi, yj) using
        // w = arrX[i] + arrY[j]
        int result = row[xFind] + col[yFind];
      
        return result;
    }
      
    // Driver code
    int main()
    {
        vector > operations
            = {
                { 0, 0, 1 },
                { 1, 1, 2 }
              };
        int n = 3,
            m = operations.size(),
            xFind = 1,
            yFind = 0;
        cout << findWeight(operations,
                           n, m, xFind,
                           yFind);
        return 0;
    }


    Python3
    # Python3 program to find the
    # weight at xi and yi
      
    # Function to calculate weight at (xFind, yFind)
    def findWeight(operations, n, m, xFind, yFind) :
      
        row = [ 0 ] * n
        col = [ 0 ] * n
       
        # Loop to perform operations
        for i in range(m) :
       
            # Updating row
            row[operations[i][0]]+= operations[i][2]
       
            # Updating column
            col[operations[i][0]]+= operations[i][2]
       
        # Find weight at (xi, yj) using
        # w = arrX[i] + arrY[j]
        result = row[xFind] + col[yFind]
       
        return result
       
    # Driver code
    operations = [[ 0, 0, 1 ],[ 1, 1, 2 ]]
    n = 2
    m = len(operations)
    xFind = 1
    yFind = 0
    print(findWeight(operations,n, m, xFind, yFind))
      
    # This code is contributed by divyamohan123



    输出:
    3

    时间复杂度:  O(m)其中 m 是操作次数

    如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。