Codeforces Round #675 (Div. 2) B. Nice Matrix

B. Nice Matrix

A matrix of size n×m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a1,a2,…,ak) is a palindrome, if for any integer i (1≤i≤k) the equality ai=ak−i+1 holds.

Sasha owns a matrix a of size n×m. In one operation he can increase or decrease any number in the matrix by one. Sasha wants to make the matrix nice. He is interested what is the minimum number of operations he needs.

Help him!

Input

The first line contains a single integer t — the number of test cases (1≤t≤10). The t tests follow.

The first line of each test contains two integers n and m (1≤n,m≤100) — the size of the matrix.

Each of the next n lines contains m integers ai,j (0≤ai,j≤109) — the elements of the matrix.

Output

For each test output the smallest number of operations required to make the matrix nice.

Example
inputCopy
2
4 2
4 2
2 4
4 2
2 4
3 4
1 2 3 4
5 6 7 8
9 10 11 18
outputCopy
8
42
Note

In the first test case we can, for example, obtain the following nice matrix in 8 operations:

2 2
4 4
4 4
2 2
In the second test case we can, for example, obtain the following nice matrix in 42 operations:

5 6 6 5
6 6 6 6
5 6 6 5

题意: 有t组测试案例,每组测试案例的第一行输入一个矩阵的行和列(分别用n、m表示)。接下来的n行每行有m个数,代表矩阵中的数字。现要求经过多少最少步的加减操作使得该矩阵的行、列是回文数。每次对一个数操作,只能是加一或者是减一。

题解: 因为矩阵中的 a [ i ] [ o ] a[i][o] a[i][o]只与 a [ n − i − 1 ] [ o ] 、 a [ i ] [ m − o − 1 ] a[n-i-1][o]、a[i][m-o-1] a[ni1][o]a[i][mo1]有关,所有我们可以将这三个数从大到小进行排序,这样最大值、最小值到中间值(排完序之后的中间那个值)即为它们操作的最小的步数。

c++ AC 代码

#include <cstdio>
#include <vector>
#include <algorithm>
typedef long long ll;

int mt[110][110];
int n, m;

int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		ll res = 0;
		scanf("%d%d", &n, &m);
		for (int i = 0; i < n; i++)
			for (int o = 0; o < m; o++)
				scanf("%d", &mt[i][o]);

		for (int i = 0; i < n; i++)
			for (int o = 0; o < m; o++)
			{
				std::vector<int> v;
				v.push_back(mt[i][o]);
				v.push_back(mt[n - i - 1][o]);
				v.push_back(mt[i][m - o - 1]);
				sort(v.begin(),v.end());

				res += v[2]- v[1];
				res += v[1] - v[0];
				mt[i][o] = mt[n-i-1][o] = mt[i][m-o-1] = v[1];
			}
		
		printf("%lld\n",res);
	}
	return 0;
}

代码参考自:https://blog.csdn.net/henulmh/article/details/108963198

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值