📌  相关文章
📜  最多翻转二进制矩阵 K 次后的最高分

📅  最后修改于: 2021-10-27 03:18:29             🧑  作者: Mango

给定一个由零和一组成的二维矩阵A和一个整数K
在每次移动中,您可以选择任何行或列并切换该行或列中的每个值。即,将所有0更改为 1 ,或将所有1 更改为 0 。最多进行 K 次移动后,该矩阵的每一行代表一个二进制数。
任务是返回这些数字之和的最大可能值。
例子

Input : A[][] = { { 0, 0, 1, 1 }, 
                  { 1, 0, 1, 0 }, 
                  { 1, 1, 0, 0 } }; 
        K = 2
Output : 36

Input : A[][] = { { 0, 1 }, 
                  { 1, 0 }, 
                  { 1, 1 } }; 
        K = 1
Output : 7

请注意,从右数第 i 列中的1为分数贡献了2 i
也知道一个事实, 2^{n} > 2^{n-1}+2^{n-2}+2^{n-3}+...2^{0}  ,最大化最左边的数字比任何其他数字都更重要。因此,任何行都应该被切换,这样最左边的列应该全为0或全为1 (以便在切换最左边的列 [如有必要] 后,左列全为1 )。
现在,对于第一个元素为 0 的行,创建一个映射,以 row 的作为,该行的索引作为element 。现在我们用最小值切换行,以便更新后它对我们的总分贡献最大。
现在,其他后续列数我们总

  • 如果( zeros >ones and K > 0 )我们切换列并将我们的答案更新为ans = ans + zero * pow( 2, columns – j – 1) ,对于所有1 \leq j \leq columns - 1  并将K减一。
  • 否则我们将答案更新为ans = ans + one * pow( 2, columns – j – 1) ,对于所有1 \leq j \leq columns - 1  .

下面是上述方法的实现:

C++
// C++ program to find the maximum score after
// flipping a Binary Matrix atmost K times
#include 
using namespace std;
 
const int n = 3;
const int m = 4;
 
// Function to find maximum score of matrix
int maxMatrixScore(int A[n][m], int K)
{
    map update;
 
    // find value of rows having first
    // column value equal to zero
    for (int i = 0; i < n; ++i) {
        if (A[i][0] == 0) {
            int ans = 0;
 
            for (int j = 1; j < m; ++j)
                ans = ans + A[i][j] * pow(2, m - j - 1);
 
            update[ans] = i;
        }
    }
 
    // update those rows which lead to
    // maximum score after toggle
    map::iterator it = update.begin();
 
    while (K > 0 && it != update.end()) {
 
        int idx = it->second;
 
        for (int j = 0; j < m; ++j)
            A[idx][j] = (A[idx][j] + 1) % 2;
 
        it++;
        K--;
    }
 
    // Calculating answer
    int ans = 0;
 
    for (int j = 0; j < m; ++j) {
 
        int zero = 0, one = 0;
 
        for (int i = 0; i < n; ++i) {
            A[i][j] == 0 ? zero++ : one++;
        }
 
        // check if K > 0 we can toggle if necessary.
        if (K > 0 && zero > one) {
            ans += zero * pow(2, m - j - 1);
            K--;
        }
        else
            ans += one * pow(2, m - j - 1);
    }
 
    // return max answer possible
    return ans;
}
 
// Driver program
int main()
{
    int A[n][m] = { { 0, 0, 1, 1 },
                    { 1, 0, 1, 0 },
                    { 1, 1, 0, 0 } };
    int K = 2;
    // function call to print required answer
    cout << maxMatrixScore(A, K);
 
    return 0;
}


Java
// Java program to find the maximum score after
// flipping a Binary Matrix atmost K times
import java.util.*;
 
class GFG
{
 
static int n = 3;
static int m = 4;
 
// Function to find maximum score of matrix
static int maxMatrixScore(int A[][], int K)
{
    HashMap update =
        new HashMap();
 
    // find value of rows having first
    // column value equal to zero
    for (int i = 0; i < n; ++i)
    {
        if (A[i][0] == 0)
        {
            int ans = 0;
 
            for (int j = 1; j < m; ++j)
                ans = (int) (ans + A[i][j] *
                        Math.pow(2, m - j - 1));
 
            update.put(ans, i);
        }
    }
 
    // Update those rows which lead to
    // maximum score after toggle
    for (Map.Entry it : update.entrySet())
    if (K > 0 )
    {
        int idx = it.getValue();
 
        for (int j = 0; j < m; ++j)
            A[idx][j] = (A[idx][j] + 1) % 2;
 
        K--;
    }
 
    // Calculating answer
    int ans = 0;
 
    for (int j = 0; j < m; ++j)
    {
 
        int zero = 0, one = 0;
 
        for (int i = 0; i < n; ++i)
        {
            if(A[i][j] == 0)
                zero++;
            else
                one++;
        }
 
        // Check if K > 0 we can toggle if necessary.
        if (K > 0 && zero > one)
        {
            ans += zero * Math.pow(2, m - j - 1);
            K--;
        }
        else
            ans += one * Math.pow(2, m - j - 1);
    }
 
    // return max answer possible
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int A[][] = { { 0, 0, 1, 1 },
                    { 1, 0, 1, 0 },
                    { 1, 1, 0, 0 } };
    int K = 2;
     
    // function call to print required answer
    System.out.print(maxMatrixScore(A, K));
}
}
 
// This code is contributed by PrinciRaj1992


Python3
# Python3 program to find the maximum
# score after flipping a Binary Matrix
# atmost K times
 
n = 3
m = 4
 
# Function to find maximum score of matrix
def maxMatrixScore(A, K):
 
    update = {}
 
    # Find value of rows having first
    # column value equal to zero
    for i in range(0, n):
        if A[i][0] == 0:
             
            ans = 0
            for j in range(1, m):
                ans = ans + A[i][j] * 2 ** (m - j - 1)
 
            update[ans] = i
         
    # update those rows which lead to
    # maximum score after toggle
    for idx in update.values():
 
        for j in range(0, m):
            A[idx][j] = (A[idx][j] + 1) % 2
 
        K -= 1
        if K <= 0:
            break
 
    # Calculating answer
    ans = 0
    for j in range(0, m):
         
        zero, one = 0, 0
 
        for i in range(0, n):
            if A[i][j] == 0: zero += 1
            else: one += 1
 
        # check if K > 0 we can
        # toggle if necessary.
        if K > 0 and zero > one:
            ans += zero * 2 ** (m - j - 1)
            K -= 1
         
        else:
            ans += one * 2 ** (m - j - 1)
     
    # return max answer possible
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    A = [[0, 0, 1, 1],
         [1, 0, 1, 0],
         [1, 1, 0, 0]]
     
    K = 2
     
    # function call to print required answer
    print(maxMatrixScore(A, K))
 
# This code is contributed by Rituraj Jain


C#
// C# program to find the maximum score after
// flipping a Binary Matrix atmost K times
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int n = 3;
static int m = 4;
 
// Function to find maximum score of matrix
static int maxMatrixScore(int [,]A, int K)
{
    Dictionary update =
        new Dictionary();
 
    // find value of rows having first
    // column value equal to zero
    int ans=0;
    for (int i = 0; i < n; ++i)
    {
        if (A[i, 0] == 0)
        {
            ans = 0;
 
            for (int j = 1; j < m; ++j)
                ans = (int) (ans + A[i, j] *
                        Math.Pow(2, m - j - 1));
 
            update.Add((int)ans, i);
        }
    }
 
    // Update those rows which lead to
    // maximum score after toggle
    foreach(KeyValuePair it in update)
    if (K > 0 )
    {
        int idx = it.Value;
 
        for (int j = 0; j < m; ++j)
            A[idx, j] = (A[idx, j] + 1) % 2;
 
        K--;
    }
 
    // Calculating answer
    ans = 0;
 
    for (int j = 0; j < m; ++j)
    {
 
        int zero = 0, one = 0;
 
        for (int i = 0; i < n; ++i)
        {
            if(A[i, j] == 0)
                zero++;
            else
                one++;
        }
 
        // Check if K > 0 we can toggle if necessary.
        if (K > 0 && zero > one)
        {
            ans += zero * (int)Math.Pow(2, m - j - 1);
            K--;
        }
        else
            ans += one * (int)Math.Pow(2, m - j - 1);
    }
 
    // return max answer possible
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int [,]A = { { 0, 0, 1, 1 },
                    { 1, 0, 1, 0 },
                    { 1, 1, 0, 0 } };
    int K = 2;
     
    // function call to print required answer
    Console.Write(maxMatrixScore(A, K));
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

36

时间复杂度: O(N*M)

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