【Codeforces 1422 B】Nice Matrix,贪心,回文矩阵

problem

B. Nice Matrix
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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

solution
/*
题意:
+ 给出一个n*m(100)的矩阵,每次可以修改1,求最少多少次使得矩阵行列都回文
思路:
+ 对于a[x][y],因为行列回文,所以a[x][y]=a[n-x+1][y]=a[x][m-y+1]=a[n-x+1][m-y+1],答案就是这四个的中位数。
+ 像这样找规律然后选定某种策略直接计算的题算是贪心题
*/
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 110;
LL a[maxn][maxn];
int main(){
	ios::sync_with_stdio(false);
	int T;  cin>>T;
	while(T--){
		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 ans = 0;
		int rl=1, rr = n;
		while(rl <= rr){
			int cl = 1, cr = m;
			while(cl <= cr){
				vector<LL>num;
				num.push_back(a[rl][cl]);
				if(rl!=rr)num.push_back(a[rr][cl]);
				if(cl!=cr)num.push_back(a[rl][cr]);
				if(cl!=cr && rl!=rr)num.push_back(a[rr][cr]);
				
				LL tmp = 0;
				sort(num.begin(),num.end());
				for(int i = 0; i < num.size(); i++)
					tmp += abs(num[i]-num[num.size()/2]);
				ans += tmp;
				
				cl++, cr--;
			}
			rl++, rr--;
		}
		cout<<ans<<"\n";
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小哈里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值