A. Weird Sum
Examples
input
2 3
1 2 3
3 2 1
output
7
input
3 4
1 1 2 2
2 1 1 2
2 2 1 1
output
76
input
4 4
1 1 2 3
2 1 1 2
3 1 2 1
1 1 2 1
output
129
Note
In the first sample there are three pairs of cells of same color: in cells (1,1)and(2,3), in cells(1,2) and (2,2), in cells (1,3)and(2,1). The manhattan distances between them are 3, 1 and 3, the sum is 7.
一道想了两天的题目。
题目大意:
一个n*m的矩阵,求所有相同元素之间的曼哈顿距离之和。
思路:
先把相同的数字分到一组,因为曼哈顿距离等于|xi-xj|+|yi-yj|,所以可以把x和y分别计算,不妨先抽离出每个数的x坐标,那么问题就变成了求 x1 x2 … xn 中两两距离的和。(快速求这个和让我想了好久)。
先考虑简单的情况,当x中,没有重复的数时,答案就是相邻两数差的前缀和。
比如 1 3 5 7 11 那么差就是 2 2 2 4 前缀和就是 2 4 6 10
但是实际上是有重复数字的,不方便直接算,可以反着算。
比如 1 1 2 2 3 4 我们算3对3之前的数的贡献,3-1+3-1+3-2+3-2=6
其实就是3*4-1-1-2-2,也就是 当前的数 * 前面的数的个数 - 前缀和
那么答案就出来了,ans += xi * (i - 1) * sum(i - 1)
代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<map>
#define endl '\n'
using namespace std;
const int N=1e6+7;
map<int,vector<int>>mp1,mp2;
long long solve(map<int,vector<int>>&s)
{
long long ans=0;
for(auto temp:s)
{
auto v=temp.second;
sort(v.begin(),v.end());
long long sum=0;//前缀和
long long count=0;//统计元素数量
for(auto j:v)
{
ans+=j*count-sum;
sum+=j;
count++;
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n,m;
cin>>n>>m;
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
int a;
cin>>a;
mp1[a].push_back(i);
mp2[a].push_back(j);
}
}
cout<<solve(mp1)+solve(mp2)<<endl;
return 0;
}