链接:https://codeforces.com/problemset/problem/1422/B 题意: 输入一个矩阵,每次操作可以对其中的进行+1或-1,用最少的次数让其变为回文矩阵; 题解: 对每一个,只要保证对称位置相同,那么这个矩阵就是回文;所以,只要用最少的次数使得3个位置的数相同(中位数定理);具体看代码; 代码: `#include<bits/stdc++.h> using namespace std; typedef long long ll; int a[105][105] = { 0 };
int main() { int t; cin >> t; while (t–) { int n, m; memset(a, 0, sizeof(a)); cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> a[i][j]; } } ll ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int b[3] = { 0 }; b[0] = a[i][j]; b[1] = a[n - i - 1][j]; b[2] = a[i][m - j - 1]; sort(b, b + 3); ans += abs(b[1] - a[i][j]) + abs(b[1] - a[n - i - 1][j]) + abs(b[1] - a[i][m - j - 1]); a[i][m - j - 1] = b[1]; a[n - i - 1][j] = b[1]; a[i][j] = b[1]; } } cout << ans << endl; } return 0;
} `
|