有一个二维矩阵 A ,其中每个元素的值为 0 或 1 。
翻转是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。
在做出任意次数的翻转后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。
返回尽可能高的分数。
示例:
输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]]
输出:39
解释:
转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]]
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
输入说明首先输入矩阵的行数m、列数n,
然后输入m行,每行n个数字,每个数字都是0或1。
1 <= m <= 20
1 <= n <= 20
3 4 0 0 1 1 1 0 1 0 1 1 0 0输出说明
输出一个整数
39代码思路
使用贪心算法实现,使翻转后的数字尽可能大
1、在进行行翻转时,保证每一行的第一列为1,这样可以使该位上对应的二进制数最大
2、在进行列翻转时,从第二列开始,只有当该列含有的0的个数大于1的个数时才进行翻转
具体实现如下
#include#include #include #include #include using namespace std; class Solution { public: int matrix_score(vector >& nums) { //贪心法 //每行第一列为1,若不为1,则翻转该行 //列:从第二列开始,若某列中0的个数大于1的个数,翻转该列 int row=nums.size(); int col=nums[0].size(); //行翻转 for(int i=0;i if(nums[i][0]==1){ continue; } for(int j=0;j
if(nums[i][j]==0){ nums[i][j]=1; } else nums[i][j]=0; } } //计算最高位和,第一列全为1 int res=row*pow(2,col-1); //列翻转 for(int j=1;j int cnt=0; for(int i=0;i if(nums[i][j]==1){ cnt++; } } res+=max(cnt,row-cnt)*pow(2,col-1-j); } return res; } }; int main() { int n,m,tmp; cin >> m>>n;//m代表行数, n代表列数 vector
>nums; vector data; for (int i = 0; i < m; i++) { data.clear(); for (int j = 0; j < n; j++) { cin >> tmp; data.push_back(tmp); } nums.push_back(data); } int res = Solution().matrix_score(nums); cout << res<



