AcWing 3565. 完美矩阵 java 没有PAIR, 用LONG来存,SET去重
原题链接
中等
import java.util.*;
import java.io.*;
class Main {
public static long comput(int[] tmp) {
long res = 0;
int n = tmp.length;
Arrays.sort(tmp);
for (int i = 0; i < tmp.length; i++) res += Math.abs(tmp[i] - tmp[n / 2]);
return res;
}
public static long comput1(Set<Long> set, int[][] a) throws Exception {
long res = 0;
List<Integer> list = new ArrayList<>();
for (Long num: set) {
int y = (int)(num << 32 >> 32);
int x = (int)(num >> 32);
list.add(a[x][y]);
}
Collections.sort(list);
int n = list.size();
for (int i = 0; i < n; i++) res += Math.abs(list.get(i) - list.get(n / 2));
return res;
}
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws Exception{
// Scanner sc = new Scanner(System.in);
int T = Integer.parseInt(in.readLine());
while (T-- > 0) {
String[] line = in.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
line = in.readLine().split(" ");
for (int j = 0; j < m; j++) {
a[i][j] = Integer.parseInt(line[j]);
}
}
long res = 0;
for (int i = 0; i <= n - 1 - i; i++) {
for (int j = 0; j <= m - 1 - j; j++) {
Set<Long> set = new HashSet<>();
set.add(((long)i<<32) + j);
set.add(((long)(n - 1 - i)<<32) + j);
set.add(((long)(n - 1 - i)<<32) + m - 1 - j);
set.add(((long)i<<32) + m - 1 - j);
res += comput1(set, a);
}
}
out.write(res+"\n");
}
out.flush();
}
}