import sys def compute_sum(x, homes): total = 0 for (a, c) in homes: total += max(abs(a - x), c) return total def find_optimal_x(homes, N): low = 1 high = N while high - low > 3: mid1 = low + (high - low) // 3 mid2 = high - (high - low) // 3 s1 = compute_sum(mid1, homes) s2 = compute_sum(mid2, homes) if s1 < s2: high = mid2 else: low = mid1 min_sum = float('inf') for x in range(low, high + 1): current = compute_sum(x, homes) if current < min_sum: min_sum = current return min_sum def main(): input = sys.stdin.read().split() ptr = 0 N = int(input[ptr]) ptr += 1 homes = [[] for _ in range(N + 1)] for i in range(N): for j in range(N): k = int(input[ptr]) ptr += 1 a = i + 1 b = j + 1 c = abs(b - 1) homes[k].append((a, c)) total = 0 for k in range(1, N + 1): min_sum = find_optimal_x(homes[k], N) total += min_sum print(total) if __name__ == '__main__': main()