Skip to content

Commit c5f4370

Browse files
Create Matrix Transformation.cpp
1 parent 5dd77c4 commit c5f4370

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
5+
using namespace std;
6+
7+
void read(vector <vector <int> > &M, int rows, int columns)
8+
{
9+
for(int i = 1; i <= rows; i++)
10+
{
11+
for(int j = 1; j <= columns; j++)
12+
{
13+
cin >> M[i][j];
14+
}
15+
}
16+
}
17+
18+
void solve()
19+
{
20+
int rows, columns;
21+
cin >> rows >> columns;
22+
23+
vector <vector <int> > A(rows + 1, vector <int> (columns + 1));
24+
vector <vector <int> > B(rows + 1, vector <int> (columns + 1));
25+
read(A, rows, columns);
26+
read(B, rows, columns);
27+
28+
vector <vector <int> > C(rows + 1, vector <int> (columns + 1));
29+
for(int i = 1; i <= rows; i++)
30+
{
31+
for(int j = 1; j <= columns; j++)
32+
{
33+
C[i][j] = A[i][j] - B[i][j];
34+
}
35+
}
36+
37+
int possible = true;
38+
for(int i = 1; i <= rows; i++)
39+
{
40+
for(int j = 1; j <= columns; j++)
41+
{
42+
if(C[i][j] - C[i][1] != C[1][j] - C[1][1])
43+
{
44+
possible = false;
45+
}
46+
}
47+
}
48+
49+
if(!possible)
50+
{
51+
cout << "-1\n";
52+
53+
return;
54+
}
55+
56+
vector <long long> points;
57+
for(int i = 1; i <= columns; i++)
58+
{
59+
points.push_back(C[1][i]);
60+
}
61+
for(int i = 1; i <= rows; i++)
62+
{
63+
points.push_back(C[1][1] - C[i][1]);
64+
}
65+
66+
sort(points.begin(), points.end());
67+
68+
int median_index = points.size()/2 - (points.size()%2 == 0 ? 1 : 0);
69+
long long median = points[median_index];
70+
71+
long long operations = 0;
72+
73+
for(int i = 0; i < points.size(); i++)
74+
{
75+
operations += abs(points[i] - median);
76+
}
77+
78+
cout << operations << "\n";
79+
}
80+
81+
int main()
82+
{
83+
int no_of_test_cases;
84+
cin >> no_of_test_cases;
85+
86+
while(no_of_test_cases--)
87+
solve();
88+
89+
return 0;
90+
}

0 commit comments

Comments
 (0)