Codeforces 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.

题意:给你一个 n × m 的矩阵,你可以对其中的任意元素进行自增或自减1操作。问你至少要经过多少次操作才能使得它变成nice矩阵?nice矩阵的定义为:任一行或任一列都是回文序列。

题解:这题直接模拟即可解决,在矩阵中的每个元素,都只和两个元素有关系,比如 a[i][j]只和 a[i][m-j+1]、a[n-i+1][j] 有关系,需要变换使这三个元素值相等,那么怎么才操作最小呢?排个序,然后最大的值和最小的值都向中间值靠拢操作最小。然后更新矩阵值。遍历一遍矩阵,即可得解。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
	int t,n,m,a[105][105];
	cin>>t;
	while(t--)
	{
		ll cnt=0;
		cin>>n>>m;
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=m;j++)
			{
				cin>>a[i][j];
			}
		}
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=m;j++)
			{
				vector<int> v;
				v.push_back(a[i][j]);
				v.push_back(a[n-i+1][j]);
				v.push_back(a[i][m-j+1]);
				sort(v.begin(),v.end());
				cnt+=v[2]-v[1];
				cnt+=v[1]-v[0];
				a[i][j]=a[n-i+1][j]=a[i][m-j+1]=v[1];
			}
		}
		cout<<cnt<<endl;
	} 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

henulmh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值