ในปัญหานี้ เราได้รับเมทริกซ์สองตัวคือ 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