原文
Egor has a table of sizen×m, with lines numbered from 1 to n and columns numbered from 1 to m. Each cell has a color that can be presented as an integer from 1 to 105.
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) and (3,3)is 3, one of the shortest paths is the following: (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≤100000) — number of rows and columns in the table.
Each of next nn lines describes a row of the table. The i-th line contains mm integers ci1,ci2,…,cim (1≤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
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.
思路:
1,首先看数据范围,O(n^3)不被允许,可先写然后优化
2,优化:行,当前行算出和之前所有的数的差(前缀和);列,当前列算出和之前的所有数的差,
注意//:行,列,先小后大.
代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxj=1e5+100;
vector<int>v[maxj];
int sum[maxj],cnt[maxj];
int32_t main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n,m;
cin>>n>>m;
int ans=0;
for(int i=1;i<=n;++i){//算行的差值
for(int j=1;j<=m;++j){
int x;
cin>>x;
v[i].push_back(x);
ans+=cnt[x]*i-sum[x];
sum[x]+=i;//前缀和,统一减前面的和
cnt[x]++;
}
}
memset(sum,0,sizeof(sum));
memset(cnt,0,sizeof(cnt));
for(int j=1;j<=m;++j){算列的差值,一定得先列,由小列到大列
for(int i=1;i<=n;++i){
int x=v[i][j-1];
ans+=cnt[x]*j-sum[x];
sum[x]+=j;
cnt[x]++;
}
}
cout<<ans;
return 0;
}