n,m = map(int,input().split())
mat = []
for i in range(n):
mat.append(list(map(int,input().split())))
d={}
for i in range(n):
for j in range(m):
if mat[i][j] not in d:
d[mat[i][j]] = [[i+1,j+1]]
else:
d[mat[i][j]].append([i+1,j+1])
sumx=[0]*(len(d))
sumy=[0]*(len(d))
for num,i in enumerate(d):
for j in d[i]:
sumx[num]+=j[0]
sumy[num]+=j[1]
ans=0
for i,ele in enumerate(d):
c = len(d[ele])
d[ele].sort()
for curr,ind in enumerate(d[ele]):
if curr>=c-1:
break
ans +=abs(sumx[i]-ind[0] - (c-curr-1)*ind[0])
sumx[i]-=ind[0]
for i,ele in enumerate(d):
c = len(d[ele])
d[ele].sort(key=lambda x:-x[1])
for curr,ind in enumerate(d[ele]):
if curr>=c-1:
break
ans +=abs(sumy[i]-ind[1] - (c-curr-1)*ind[1])
sumy[i]-=ind[1]
print(ans)
/*+Rainybunny+*/
#include <bits/stdc++.h>
#define rep(i, l, r) for (int i = l, rep##i = r; i <= rep##i; ++i)
#define per(i, r, l) for (int i = r, per##i = l; i >= per##i; --i)
typedef long long LL;
typedef std::pair<int, int> PII;
#define fi first
#define se second
inline char fgc() {
static char buf[1 << 17], *p = buf, *q = buf;
return p == q && (q = buf + fread(p = buf, 1, 1 << 17, stdin), p == q) ?
EOF : *p++;
}
template <typename Tp = int>
inline Tp rint() {
Tp x = 0, s = fgc(), f = 1;
for (; s < '0' || '9' < s; s = fgc()) f = s == '-' ? -f : f;
for (; '0' <= s && s <= '9'; s = fgc()) x = x * 10 + (s ^ '0');
return x * f;
}
template <typename Tp>
inline void wint(Tp x) {
if (x < 0) putchar('-'), x = -x;
if (9 < x) wint(x / 10);
putchar(x % 10 ^ '0');
}
const int MAXC = 1e5;
int n, m;
std::vector<std::vector<int> > c;
std::vector<PII> buc[MAXC + 5];
inline LL calc(const int u) {
if (buc[u].empty()) return 0;
std::sort(buc[u].begin(), buc[u].end());
int s = buc[u].size();
LL ret = 0, pre = 0;
rep (i, 0, s - 1) {
ret += 1ll * buc[u][i].fi * i - pre, pre += buc[u][i].fi;
}
std::sort(buc[u].begin(), buc[u].end(),
[](const PII& x, const PII& y) { return x.se < y.se; });
pre = 0;
rep (i, 0, s - 1) {
ret += 1ll * buc[u][i].se * i - pre, pre += buc[u][i].se;
}
return ret;
}
int main() {
n = rint(), m = rint();
rep (i, 1, n) rep (j, 1, m) buc[rint()].push_back({ i, j });
LL ans = 0;
rep (i, 1, MAXC) ans += calc(i);
wint(ans), putchar('\n');
return 0;
}
405A - Gravity Flip | 499B - Lecture |
709A - Juicer | 1358C - Celex Update |
1466B - Last minute enhancements | 450B - Jzzhu and Sequences |
1582C - Grandma Capa Knits a Scarf | 492A - Vanya and Cubes |
217A - Ice Skating | 270A - Fancy Fence |
181A - Series of Crimes | 1638A - Reverse |
1654C - Alice and the Cake | 369A - Valera and Plates |
1626A - Equidistant Letters | 977D - Divide by three multiply by two |
1654B - Prefix Removals | 1654A - Maximum Cake Tastiness |
1649A - Game | 139A - Petr and Book |
1612A - Distance | 520A - Pangram |
124A - The number of positions | 1041A - Heist |
901A - Hashing Trees | 1283A - Minutes Before the New Year |
1654D - Potion Brewing Class | 1107B - Digital root |
25A - IQ test | 785A - Anton and Polyhedrons |