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
题意
给你一个矩阵,你有一种操作可以使矩阵的任意一个数+1或-1,问你如何操作最少的次数使得矩阵的每一行,每一列均为回文
思路
给出一个示范矩阵
观察矩阵,以第一行第一列的数举例
当操作结束时,第一列应当为回文
所以第一行第一列与第五行第一列数应该相等
第一行也应当为回文
所以第一行第一列与第一行第5列相等
以此类推
红色颜色的点数字应当相同
所以选择最小的步数让这几道题
显然
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;
long long map[200][200];
int main(void) {
int t;
scanf("%d",&t);
while(t--) {
int n,m;
memset(map,0,sizeof(map));
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
scanf("%lld",&map[i][j]);
}
}
unsigned long long ans=0;
for(int i=0;i<n/2;i++) {
for(int j=0;j<m/2;j++) {
long long temp[4];
temp[0]=map[i][j];
temp[1]=map[n-i-1][j];
temp[2]=map[n-i-1][m-j-1];
temp[3]=map[i][m-j-1];
sort(temp,temp+4);
ans+=abs(temp[0]-temp[2])+abs(temp[1]-temp[2])+abs(temp[3]-temp[2]);
}
}
if(n%2==1) {
for(int j=0;j<m/2;j++) {
ans+=abs(map[n/2][j]-map[n/2][m-j-1]);
}
}
if(m%2==1) {
for(int i=0;i<n/2;i++) {
ans+=abs(map[i][m/2]-map[n-i-1][m/2]);
}
}
printf("%lld\n",ans);
}
}