We have a two dimensional matrix A
where each value is 0
or 1
.
A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0
s to 1
s, and all 1
s to 0
s.
After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]] Output: 39 Explanation: Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]]. 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
一个由0和1构成的矩阵,每次可以选择任意一行或列,行或列的数字0变成1,1变成0.
每一行代表一个二进制数,求能够成的这些二进制数和的最大值
由二进制转十进制原理,1的位置越靠前越好,所以第一步,把每一行的第一个数变成1.
第二步,对除了第一列外的每一列的1的个数做统计,如果翻转后能增加1的个数,就翻转该列。
1 class Solution { 2 public: 3 int matrixScore(vector<vector<int>>& A) { 4 int row = A.size(); 5 int col = A[0].size(); 6 vector<int> cnt(col, 0); 7 for (int i = 0; i < row; ++i) { 8 if (A[i][0] == 0) { 9 for (int j = 0; j < col; ++j) { 10 A[i][j] = 1 - A[i][j]; 11 if (A[i][j] == 1) ++cnt[j]; 12 } 13 } 14 else { 15 for (int j = 0; j < col; ++j) { 16 if (A[i][j] == 1) ++cnt[j]; 17 } 18 } 19 } 20 for (int j = 1; j < col; ++j) { 21 if (cnt[j] * 2 < row) { 22 for (int i = 0; i < row; ++i) 23 A[i][j] = 1 - A[i][j]; 24 } 25 } 26 int sum = 0; 27 int v = 0;; 28 int res = 0; 29 for (int i = 0; i < row; ++i) { 30 sum = 0; 31 v = 1; 32 for (int j = col - 1; j >= 0; --j) { 33 sum += A[i][j] * v; 34 v = v * 2; 35 } 36 res += sum; 37 } 38 return res; 39 } 40 };
原文地址:https://www.cnblogs.com/Zzz-y/p/9275410.html
时间: 2024-10-08 06:13:59