在C++中查找使两个矩阵相等的变换次数
在这个问题中,我们得到了两个相同大小的矩阵mat1[][]和mat2[][]。我们的任务是找到使两个矩阵相等的变换次数。
矩阵变换如下:
选择两个矩阵中的任意一个矩阵。
从矩阵中选择一行或一列。
将所选行或列的所有元素加1。
让我们举个例子来理解这个问题:
输入
mat1[][] = {{1 2}
{2 1}}
mat1[][] = {{2 3}
{4 3}}输出
3
解释
1 2 => 2 2 => 2 3 => 2 3 2 1 => 3 1 => 3 2 => 4 3
解决方案方法
解决这个问题的一个简单方法是找出变换是否可行。为此,我们需要检查:
if( mat[i][j] - mat[i][0] - mat[0][j] + mat[0][0] != 0 )
如果没有,则不存在解决方案。
现在,如果变换是可能的,我们将计算行和列的变换次数。
程序说明了我们解决方案的工作原理:
示例
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
int countTransformationReq(int mat1[][MAX], int mat2[][MAX],
int m, int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
mat1[i][j] -= mat2[i][j];
for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++)
if (mat1[i][j] - mat1[i][0] - mat1[0][j] +
mat1[0][0] != 0)
return -1;
int trxCount = 0;
for (int i = 0; i < n; i++)
trxCount += abs(mat1[i][0]);
for (int j = 0; j < m; j++)
trxCount += abs(mat1[0][j] - mat1[0][0]);
return (trxCount);
}
int main() {
int mat1[MAX][MAX] = { {1, 2}, {2, 1}};
int mat2[MAX][MAX] = { {2, 3}, {4, 3}};
cout<<"The number of transformation to make the teo
maxtrces equal are "<<countTransformationReq(mat1, mat2, 2,
2) ;
return 0;
}输出
The number of transformation to make the teo maxtrces equal are 3
高效方法
解决这个问题的一个更有效的方法是使用握手定理。
我们将创建一个temp[]数组来计算数组模数中0和1的出现次数。然后返回计数值。
程序说明了我们解决方案的工作原理:
示例
#include<iostream>
using namespace std;
int countEvenSumSubArray(int arr[], int n){
int temp[2] = {1, 0};
int count = 0, sum = 0;
for (int i=0; i<=n-1; i++){
sum = ( (sum + arr[i]) % 2 + 2) % 2;
temp[sum]++;
}
count += (temp[0]*(temp[0]-1)/2);
count += (temp[1]*(temp[1]-1)/2);
return (count);
}
int main(){
int arr[] = {2, 1, 4, 2};
int n = sizeof (arr) / sizeof (arr[0]);
cout<<"The count of Subarrays with even sum is "<<countEvenSumSubArray(arr, n);
return (0);
}输出
The count of Subarrays with even sum is 4
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP