题目链接:Problem - C - Codeforces
题目描述:
输入描述:
?
输出描述:
?
样例及解释:
?
题意:有一个n * m的矩阵,表示为[n, m],每个点上面有一个颜色,现在求每对相同颜色的点的曼哈顿距离
思路:曼哈顿距离的求解是abs(x1 - x2) + abs(y1 - y2)
那么我们就可以把每个点的横纵坐标分开保存,然后排序,进行求值累加
#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<int> l[100005], r[100005];
int main(){
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
int a;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> a;
l[a].push_back(i);
r[a].push_back(j);
}
}
ll sum = 0;
for(int i = 1; i <= 100000; i++){
sort(l[i].begin(), l[i].end());
sort(r[i].begin(), r[i].end());
int len = l[i].size();
ll ans = 0;
ll ans1 = 0;
for(int j = 1; j < len; j++){
ans += (l[i][j] - l[i][j - 1]) * j;
sum += ans;
}
len = r[i].size();
for(int j = 1; j < len; j++){
ans1 += (r[i][j] - r[i][j - 1]) * j;
sum += ans1;
}
}
cout << sum << endl;
return 0;
}
?
|