CF1648A 题解
Description
给定一个
Solution
令序列
相应地,我们可以使用 sort 将列数序列排序为非单调递减的,所以在最终同一个数字的曼哈顿距离之和可以这样表示:
所以,当序列
Code
#include<iostream>
#include<algorithm>
#include<vector>
#define int long long //记得开 long long
#define maxn 100005
using namespace std;
int n, m, cnt[maxn];
int ans;
struct node {
int x, y;
bool operator < (const node & a) const {
return a.y < y;
}
};
vector<node> v[maxn];
signed main() {
cin >> n >> m;
for(int i = 1, a; i <= n; ++ i) {
for(int j = 1; j <= m; ++ j) {
cin >> a; ++ cnt[a];
v[a].push_back((node){i, j});
}
}
for(int i = 1; i < maxn; ++ i) {
if(v[i].empty()) continue;
for(int j = cnt[i] - 1; j >= 0; -- j) {
ans -= (cnt[i] - j - 1) * v[i][j].x;
ans += j * v[i][j].x;
}
sort(v[i].begin(), v[i].end());
for(int j = 0; j < cnt[i]; ++ j) {
ans += (cnt[i] - j - 1) * v[i][j].y;
ans -= j * v[i][j].y;
}
}
cout << ans;
return 0;
}