算法1
为了矩阵完美,需要每个四元组(上下左右对称的四个点)内的值一样
使得每个四元组一样的修改值最小,取中位数即可(绝对值不等式)
时间复杂度 $O(nm)$
参考文献
C++ 代码
略丑,加了考虑奇数的情况
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = 104;
int a[N][N];
void solve()
{
int n, m;
cin >> n>>m;
for (int i = 1;i<=n;i++)
for (int j = 1;j<=m;j++)
cin >> a[i][j];
ll res = 0;
for (int i = 1; i <= n / 2;i++)
{
for (int j = 1; j <= m / 2;j++)
{
vector<int> vec(4);
vec[0] = a[i][j];
vec[1] = a[n - i + 1][j];
vec[2] = a[i][m - j + 1];
vec[3] = a[n - i + 1][m - j + 1];
sort(vec.begin(), vec.end());
int avg = vec[1];
res += abs(vec[0] - avg) + abs(vec[1] - avg) + abs(vec[2] - avg) + abs(vec[3] - avg);
}
if(m%2)
{
int b = a[i][m / 2 + 1];
int c = a[n - i + 1][m / 2 + 1];
res += abs(b - c);
}
}
if(n%2)
{
for (int j = 1; j <= m/2;j++)
{
int b = a[n / 2 + 1][j];
int c = a[n / 2 + 1][m - j + 1];
res += abs(b - c);
}
}
cout << res << endl;
}
int main()
{
int t;
cin >> t;
while(t--)
solve();
return 0;
}