A. Weird Sum
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Egor has a table of size n×mn×m, with lines numbered from 11 to nn and columns numbered from 11 to mm. Each cell has a color that can be presented as an integer from 11 to 105105.
Let us denote the cell that lies in the intersection of the rr-th row and the cc-th column as (r,c)(r,c). We define the manhattan distance between two cells (r1,c1)(r1,c1) and (r2,c2)(r2,c2) as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table 3×43×4 the manhattan distance between (1,2)(1,2) and (3,3)(3,3) is 33, one of the shortest paths is the following: (1,2)→(2,2)→(2,3)→(3,3)(1,2)→(2,2)→(2,3)→(3,3).
Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.
Input
The first line contains two integers nn and mm (1≤n≤m1≤n≤m, n⋅m≤100000n⋅m≤100000) — number of rows and columns in the table.
Each of next nn lines describes a row of the table. The ii-th line contains mm integers ci1,ci2,…,cimci1,ci2,…,cim (1≤cij≤1000001≤cij≤100000) — colors of cells in the ii-th row.
Output
Print one integer — the the sum of manhattan distances between each pair of cells of the same color.
Examples
input
Copy
2 3 1 2 3 3 2 1
output
Copy
7
input
Copy
3 4 1 1 2 2 2 1 1 2 2 2 1 1
output
Copy
76
input
Copy
4 4 1 1 2 3 2 1 1 2 3 1 2 1 1 1 2 1
output
Copy
129
Note
In the first sample there are three pairs of cells of same color: in cells (1,1)(1,1) and (2,3)(2,3), in cells (1,2)(1,2) and (2,2)(2,2), in cells (1,3)(1,3) and (2,1)(2,1). The manhattan distances between them are 33, 11 and 33, the sum is 77.
==================================================================================================================================================
常规方法无非是对于每个数字的行列坐标存进容器n^2遍历,但很显然会超时。这里利用前缀和知识,原本我们是要对坐标进行双重循环遍历,然后再除以2,这里我们先排序,只计算一次大减小即可。对于一个v[i],v[j]小于v[i], 得到的结果是 v[i]-v[1]+v[i]-v[2]+v[i]-v[3]+...+v[i]-v[i-1]
也就是 v[i]*(i-1) +sum[i-1] 前缀和表示一下即可。
#include <bits/stdc++.h>
# define inf 0x7f7f7f7f7f7f7f7f
using namespace std;
typedef long long int ll;
vector<ll>v1[100010];
vector<ll>v2[100010];
ll sum[100010];
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
ll x;
cin>>x;
v1[x].push_back(i);
v2[x].push_back(j);
}
}
ll ans=0;
for(ll i=1;i<=100000;i++)
{
sort(v1[i].begin(),v1[i].end());
sort(v2[i].begin(),v2[i].end());
for(ll j=0;j<v1[i].size();j++)
{
sum[j+1]=sum[j]+v1[i][j];
}
// ai-a1 ai-a2 ai-a3 ai-ai-1
for(ll j=0;j<v1[i].size();j++)
{
ans+=j*v1[i][j];
ans-=sum[j];
}
for(ll j=0;j<v2[i].size();j++)
{
sum[j+1]=sum[j]+v2[i][j];
}
// ai-a1 ai-a2 ai-a3 ai-ai-1
for(ll j=0;j<v2[i].size();j++)
{
ans+=j*v2[i][j];
ans-=sum[j];
}
}
cout<<ans;
return 0;
}