📜  给定类型的最小运算,以使矩阵的所有元素相等

📅  最后修改于: 2021-06-01 01:51:30             🧑  作者: Mango

给定整数KNM列的矩阵,任务是找到使矩阵的所有元素相等所需的最小操作数。在单个操作中,可以将K添加到矩阵的任何元素或从矩阵的任何元素中减去。如果无法打印,请打印-1
例子:

方法:由于只允许从任何元素中添加或减去K ,所以我们可以轻松推断出所有包含K的元素的数应该相等,因为x%K =(x + K)%K =(x – K)% ķ。
如果不是这种情况,只需打印-1即可。否则,以非降序对矩阵的所有元素进行排序,然后找到排序后的元素的中位数。如果我们将所有元素转换为等于中位数,则将出现最小步数。计算这些步骤并打印结果。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the minimum
// number of operations required
int minOperations(int n, int m, int k,
                  vector >& matrix)
{
    // Create another array to
    // store the elements of matrix
    vector arr(n * m, 0);
 
    int mod = matrix[0][0] % k;
 
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            arr[i * m + j] = matrix[i][j];
 
            // If not possible
            if (matrix[i][j] % k != mod) {
                return -1;
            }
        }
    }
 
    // Sort the array to get median
    sort(arr.begin(), arr.end());
 
    int median = arr[(n * m) / 2];
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
        minOperations += abs(arr[i] - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0)
    {
       int median2 = arr[(n * m) / 2];
       int minOperations2 = 0;
       for (int i = 0; i < n * m; ++i)
          minOperations2 += abs(arr[i] - median2) / k;
 
       minOperations = min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
int main()
{
    vector > matrix = { { 2, 4, 6 },
                                    { 8, 10, 12 },
                                    { 14, 16, 18 },
                                    { 20, 22, 24 } };
    int n = matrix.size();
    int m = matrix[0].size();
    int k = 2;
    cout << minOperations(n, m, k, matrix);
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m,
                        int k, int matrix[][])
    {
        // Create another array to
        // store the elements of matrix
        int [] arr = new int[n * m];
     
        int mod = matrix[0][0] % k;
     
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < m; ++j)
            {
                arr[i * m + j] = matrix[i][j];
     
                // If not possible
                if (matrix[i][j] % k != mod)
                {
                    return -1;
                }
            }
        }
     
        // Sort the array to get median
        Arrays.sort(arr);
     
        int median = arr[(n * m) / 2];
     
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.abs(arr[i] - median) / k;
     
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0)
        {
        int median2 = arr[(n * m) / 2];
        int minOperations2 = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations2 += Math.abs(arr[i] - median2) / k;
 
        minOperations = Math.min(minOperations, minOperations2);
        }
     
        // Return minimum operations required
        return minOperations;
    }
     
    // Driver code
    public static void main(String []args)
    {
        int matrix [][] = { { 2, 4, 6 },
                            { 8, 10, 12 },
                            { 14, 16, 18 },
                            { 20, 22, 24 } };
                             
        int n = matrix.length;
        int m = matrix[0].length;
        int k = 2;
        System.out.println(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by ihritik


Python3
# Python3 implementation of the approach
 
# Function to return the minimum
# number of operations required
def minOperations(n, m, k, matrix):
 
    # Create another array to store the
    # elements of matrix
    arr = [0] * (n * m)
 
    mod = matrix[0][0] % k
 
    for i in range(0, n):
        for j in range(0, m):
            arr[i * m + j] = matrix[i][j]
 
            # If not possible
            if matrix[i][j] % k != mod:
                return -1
 
    # Sort the array to get median
    arr.sort()
 
    median = arr[(n * m) // 2]
 
    # To count the minimum operations
    minOperations = 0
    for i in range(0, n * m):
        minOperations += abs(arr[i] - median) // k
 
    # If there are even elements, then there
    # are two medians. We consider the best
    # of two as answer.
    if (n * m) % 2 == 0:
     
        median2 = arr[(n * m) // 2]
        minOperations2 = 0
        for i in range(0, n * m):
            minOperations2 += abs(arr[i] - median2) // k
 
        minOperations = min(minOperations,
                            minOperations2)
     
    # Return minimum operations required
    return minOperations
 
# Driver code
if __name__ == "__main__":
 
    matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]]
             
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))
 
# This code is contributed by Rituraj Jain


C#
// C# implementation of the approach
using System;
 
class GFG
{
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m,
                        int k, int [,]matrix)
    {
         
        // Create another array to
        // store the elements of matrix
        int []arr = new int[n * m];
     
        int mod = matrix[0, 0] % k;
     
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < m; ++j)
            {
                arr[i * m + j] = matrix[i,j];
     
                // If not possible
                if (matrix[i,j] % k != mod)
                {
                    return -1;
                }
            }
        }
     
        // Sort the array to get median
        Array.Sort(arr);
     
        int median = arr[(n * m) / 2];
     
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.Abs(arr[i] - median) / k;
     
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0)
        {
            int median2 = arr[(n * m) / 2];
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2 += Math.Abs(arr[i] - median2) / k;
 
            minOperations = Math.Min(minOperations, minOperations2);
        }
     
        // Return minimum operations required
        return minOperations;
    }
     
    // Driver code
    public static void Main()
    {
        int [,]matrix = { { 2, 4, 6 },
                            { 8, 10, 12 },
                            { 14, 16, 18 },
                            { 20, 22, 24 } };
                             
        int n = matrix.GetLength(0);
        int m = matrix.GetLength(1);
        int k = 2;
        Console.WriteLine(minOperations(n, m, k, matrix));
    }
}
 
// This code is contributed by Ryuga


Javascript


C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the minimum
// number of operations required
int minOperations(int n, int m, int k,
                  vector >& matrix)
{
    // Create another array to
    // store the elements of matrix
    vector arr;
 
    int mod;
     
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0) {
        mod = k - (abs(matrix[0][0]) % k);
    }
    else {
        mod = matrix[0][0] % k;
    }
     
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            arr.push_back(matrix[i][j]);
 
            // adding this to handle negative elements too .
            int val = matrix[i][j];
            if (val < 0) {
                int res = k - (abs(val) % k);
                if (res != mod) {
                    return -1;
                }
            }
            else {
                int foo = matrix[i][j];
                if (foo % k != mod) {
                    return -1;
                }
            }
        }
    }
 
    // Sort the array to get median
    sort(arr.begin(), arr.end());
 
    int median = arr[(n * m) / 2];
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
        minOperations += abs(arr[i] - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0) {
 
        // changed here as in case of even elements there will be 2 medians
        int median2 = arr[((n * m) / 2) - 1];
 
        int minOperations2 = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations2 += abs(arr[i] - median2) / k;
 
        minOperations = min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
int main()
{
    vector > matrix = { { 2, 4, 6 },
                                    { 8, 10, 12 },
                                    { 14, 16, 18 },
                                    { 20, 22, 24 } };
    int n = matrix.size();
    int m = matrix[0].size();
    int k = 2;
    cout << minOperations(n, m, k, matrix);
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
class GFG
{
 
  // Function to return the minimum
  // number of operations required
  public static int minOperations(int n, int m, int k,
                                  int matrix[][])
  {
    // Create another array to
    // store the elements of matrix
    Vector arr = new Vector<>(); 
 
    int mod;
 
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0)
    {
      mod = k - (Math.abs(matrix[0][0]) % k);
    }
    else
    {
      mod = matrix[0][0] % k;
    }
 
    for (int i = 0; i < n; ++i)
    {
      for (int j = 0; j < m; ++j)
      {
        arr.add(matrix[i][j]);
 
        // adding this to handle
        // negative elements too .
        int val = matrix[i][j];
        if (val < 0)
        {
          int res = k - (Math.abs(val) % k);
          if (res != mod)
          {
            return -1;
          }
        }
        else
        {
          int foo = matrix[i][j];
          if (foo % k != mod)
          {
            return -1;
          }
        }
      }
    }
 
    // Sort the array to get median
    Collections.sort(arr);     
    int median = arr.get((n * m) / 2);
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
      minOperations += Math.abs(arr.get(i) - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0)
    {
 
      // changed here as in case of
      // even elements there will be 2 medians
      int median2 = arr.get(((n * m) / 2) - 1);
 
      int minOperations2 = 0;
      for (int i = 0; i < n * m; ++i)
        minOperations2 += Math.abs(arr.get(i) - median2) / k;
 
      minOperations = Math.min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int matrix[][] = {
      {2, 4, 6},
      {8, 10, 12},
      {14, 16, 18},
      {20, 22, 24}
    };
    int n = matrix.length;
    int m = matrix[0].length;
    int k = 2;
    System.out.println(minOperations(n, m, k, matrix));
  }
}
 
// This code is contributed by divyesh072019


Python3
# Python3 implementation of the
# above approach
 
# Function to return the minimum
# number of operations required
def minOperations(n, m, k,
                  matrix):
 
    # Create another array to
    # store the elements of
    # matrix
    arr = []
 
    # will not work for negative
    # elements, so .. adding this
    if (matrix[0][0] < 0):
        mod = k - (abs(matrix[0][0]) % k)
    else:
        mod = matrix[0][0] % k
 
    for i in range(n):
        for j in range(m):
            arr.append(matrix[i][j])
 
            # adding this to handle
            # negative elements too .
            val = matrix[i][j]
             
            if (val < 0):
                res = k - (abs(val) % k)
                if (res != mod):
                    return -1
            else:
                foo = matrix[i][j]
                if (foo % k != mod):
                    return -1
 
    # Sort the array to get median
    arr.sort()
 
    median = arr[(n * m) // 2]
 
    # To count the minimum
    # operations
    minOperations = 0
    for i in range(n * m):
        minOperations += abs(arr[i] -
                             median) // k
 
    # If there are even elements,
    # then there are two medians.
    # We consider the best of two
    # as answer.
    if ((n * m) % 2 == 0):
 
        # changed here as in case of
        # even elements there will be
        # 2 medians
        median2 = arr[((n * m) //
                        2) - 1]
 
        minOperations2 = 0
        for i in range(n * m):
            minOperations2 += abs(arr[i] -
                                  median2) / k
             
        minOperations = min(minOperations,
                            minOperations2)
 
    # Return minimum operations required
    return minOperations
 
# Driver code
if __name__ == "__main__":
 
    matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]]
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))
 
# This code is contributed by Chitranayal


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m, int k,
                      List> matrix)
    {
        // Create another array to
        // store the elements of matrix
        List arr = new List();
      
        int mod;
          
        // will not work for negative elements, so ..
        // adding this
        if (matrix[0][0] < 0) {
            mod = k - (Math.Abs(matrix[0][0]) % k);
        }
        else {
            mod = matrix[0][0] % k;
        }
          
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr.Add(matrix[i][j]);
      
                // adding this to handle negative elements too .
                int val = matrix[i][j];
                if (val < 0) {
                    int res = k - (Math.Abs(val) % k);
                    if (res != mod) {
                        return -1;
                    }
                }
                else {
                    int foo = matrix[i][j];
                    if (foo % k != mod) {
                        return -1;
                    }
                }
            }
        }
      
        // Sort the array to get median
        arr.Sort();
      
        int median = arr[(n * m) / 2];
      
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.Abs(arr[i] - median) / k;
      
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
      
            // changed here as in case of
            // even elements there will be 2 medians
            int median2 = arr[((n * m) / 2) - 1];
      
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2 += Math.Abs(arr[i] - median2) / k;
      
            minOperations = Math.Min(minOperations, minOperations2);
        }
      
        // Return minimum operations required
        return minOperations;
    }
 
  static void Main() {
    List> matrix = new List>{
        new List {2, 4, 6},
        new List {8, 10, 12},
        new List {14, 16, 18},
        new List {20, 22, 24},
    };
    int n = matrix.Count;
    int m = matrix[0].Count;
    int k = 2;
    Console.Write(minOperations(n, m, k, matrix));
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出:
36

以下是在输入矩阵中也处理负数的实现:

C++

// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the minimum
// number of operations required
int minOperations(int n, int m, int k,
                  vector >& matrix)
{
    // Create another array to
    // store the elements of matrix
    vector arr;
 
    int mod;
     
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0) {
        mod = k - (abs(matrix[0][0]) % k);
    }
    else {
        mod = matrix[0][0] % k;
    }
     
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            arr.push_back(matrix[i][j]);
 
            // adding this to handle negative elements too .
            int val = matrix[i][j];
            if (val < 0) {
                int res = k - (abs(val) % k);
                if (res != mod) {
                    return -1;
                }
            }
            else {
                int foo = matrix[i][j];
                if (foo % k != mod) {
                    return -1;
                }
            }
        }
    }
 
    // Sort the array to get median
    sort(arr.begin(), arr.end());
 
    int median = arr[(n * m) / 2];
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
        minOperations += abs(arr[i] - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0) {
 
        // changed here as in case of even elements there will be 2 medians
        int median2 = arr[((n * m) / 2) - 1];
 
        int minOperations2 = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations2 += abs(arr[i] - median2) / k;
 
        minOperations = min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
}
 
// Driver code
int main()
{
    vector > matrix = { { 2, 4, 6 },
                                    { 8, 10, 12 },
                                    { 14, 16, 18 },
                                    { 20, 22, 24 } };
    int n = matrix.size();
    int m = matrix[0].size();
    int k = 2;
    cout << minOperations(n, m, k, matrix);
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
class GFG
{
 
  // Function to return the minimum
  // number of operations required
  public static int minOperations(int n, int m, int k,
                                  int matrix[][])
  {
    // Create another array to
    // store the elements of matrix
    Vector arr = new Vector<>(); 
 
    int mod;
 
    // will not work for negative elements, so ..
    // adding this
    if (matrix[0][0] < 0)
    {
      mod = k - (Math.abs(matrix[0][0]) % k);
    }
    else
    {
      mod = matrix[0][0] % k;
    }
 
    for (int i = 0; i < n; ++i)
    {
      for (int j = 0; j < m; ++j)
      {
        arr.add(matrix[i][j]);
 
        // adding this to handle
        // negative elements too .
        int val = matrix[i][j];
        if (val < 0)
        {
          int res = k - (Math.abs(val) % k);
          if (res != mod)
          {
            return -1;
          }
        }
        else
        {
          int foo = matrix[i][j];
          if (foo % k != mod)
          {
            return -1;
          }
        }
      }
    }
 
    // Sort the array to get median
    Collections.sort(arr);     
    int median = arr.get((n * m) / 2);
 
    // To count the minimum operations
    int minOperations = 0;
    for (int i = 0; i < n * m; ++i)
      minOperations += Math.abs(arr.get(i) - median) / k;
 
    // If there are even elements, then there
    // are two medians. We consider the best
    // of two as answer.
    if ((n * m) % 2 == 0)
    {
 
      // changed here as in case of
      // even elements there will be 2 medians
      int median2 = arr.get(((n * m) / 2) - 1);
 
      int minOperations2 = 0;
      for (int i = 0; i < n * m; ++i)
        minOperations2 += Math.abs(arr.get(i) - median2) / k;
 
      minOperations = Math.min(minOperations, minOperations2);
    }
 
    // Return minimum operations required
    return minOperations;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int matrix[][] = {
      {2, 4, 6},
      {8, 10, 12},
      {14, 16, 18},
      {20, 22, 24}
    };
    int n = matrix.length;
    int m = matrix[0].length;
    int k = 2;
    System.out.println(minOperations(n, m, k, matrix));
  }
}
 
// This code is contributed by divyesh072019

Python3

# Python3 implementation of the
# above approach
 
# Function to return the minimum
# number of operations required
def minOperations(n, m, k,
                  matrix):
 
    # Create another array to
    # store the elements of
    # matrix
    arr = []
 
    # will not work for negative
    # elements, so .. adding this
    if (matrix[0][0] < 0):
        mod = k - (abs(matrix[0][0]) % k)
    else:
        mod = matrix[0][0] % k
 
    for i in range(n):
        for j in range(m):
            arr.append(matrix[i][j])
 
            # adding this to handle
            # negative elements too .
            val = matrix[i][j]
             
            if (val < 0):
                res = k - (abs(val) % k)
                if (res != mod):
                    return -1
            else:
                foo = matrix[i][j]
                if (foo % k != mod):
                    return -1
 
    # Sort the array to get median
    arr.sort()
 
    median = arr[(n * m) // 2]
 
    # To count the minimum
    # operations
    minOperations = 0
    for i in range(n * m):
        minOperations += abs(arr[i] -
                             median) // k
 
    # If there are even elements,
    # then there are two medians.
    # We consider the best of two
    # as answer.
    if ((n * m) % 2 == 0):
 
        # changed here as in case of
        # even elements there will be
        # 2 medians
        median2 = arr[((n * m) //
                        2) - 1]
 
        minOperations2 = 0
        for i in range(n * m):
            minOperations2 += abs(arr[i] -
                                  median2) / k
             
        minOperations = min(minOperations,
                            minOperations2)
 
    # Return minimum operations required
    return minOperations
 
# Driver code
if __name__ == "__main__":
 
    matrix = [[2, 4, 6],
              [8, 10, 12],
              [14, 16, 18],
              [20, 22, 24]]
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))
 
# This code is contributed by Chitranayal

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to return the minimum
    // number of operations required
    static int minOperations(int n, int m, int k,
                      List> matrix)
    {
        // Create another array to
        // store the elements of matrix
        List arr = new List();
      
        int mod;
          
        // will not work for negative elements, so ..
        // adding this
        if (matrix[0][0] < 0) {
            mod = k - (Math.Abs(matrix[0][0]) % k);
        }
        else {
            mod = matrix[0][0] % k;
        }
          
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                arr.Add(matrix[i][j]);
      
                // adding this to handle negative elements too .
                int val = matrix[i][j];
                if (val < 0) {
                    int res = k - (Math.Abs(val) % k);
                    if (res != mod) {
                        return -1;
                    }
                }
                else {
                    int foo = matrix[i][j];
                    if (foo % k != mod) {
                        return -1;
                    }
                }
            }
        }
      
        // Sort the array to get median
        arr.Sort();
      
        int median = arr[(n * m) / 2];
      
        // To count the minimum operations
        int minOperations = 0;
        for (int i = 0; i < n * m; ++i)
            minOperations += Math.Abs(arr[i] - median) / k;
      
        // If there are even elements, then there
        // are two medians. We consider the best
        // of two as answer.
        if ((n * m) % 2 == 0) {
      
            // changed here as in case of
            // even elements there will be 2 medians
            int median2 = arr[((n * m) / 2) - 1];
      
            int minOperations2 = 0;
            for (int i = 0; i < n * m; ++i)
                minOperations2 += Math.Abs(arr[i] - median2) / k;
      
            minOperations = Math.Min(minOperations, minOperations2);
        }
      
        // Return minimum operations required
        return minOperations;
    }
 
  static void Main() {
    List> matrix = new List>{
        new List {2, 4, 6},
        new List {8, 10, 12},
        new List {14, 16, 18},
        new List {20, 22, 24},
    };
    int n = matrix.Count;
    int m = matrix[0].Count;
    int k = 2;
    Console.Write(minOperations(n, m, k, matrix));
  }
}
 
// This code is contributed by divyeshrabadiya07.

输出:
36
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”