import numpy as np N = int(input()) A_list = [list(map(int, input().split())) for i in range(N)] upper_count = np.array([0 for i in range(N)]) for i in range(N): for j in range(N): upper_count[A_list[i][j] - 1] += i if i > j else j add_list = np.array([np.array([0 for i in range(N)]) for j in range(N - 1)]) minus_list = np.array([np.array([0 for i in range(N)]) for j in range(N - 1)]) for i in range(0, N - 1): for j in range(i + 1): add_list[i][A_list[i - j][j] - 1] += 1 minus_list[-(i + 1)][A_list[N - 1 - (i - j)][j] - 1] += 1 if i != 0: add_list[i] = add_list[i - 1] + add_list[i] minus_list[-(i + 1)] = minus_list[-i] + minus_list[-(i + 1)] for i in range(len(minus_list) - 1): add_list[i + 1] += add_list[i] minus_list[i + 1] += minus_list[i] result_list = add_list - minus_list min_list = np.amin(result_list, axis=0) min_list = np.vectorize(lambda a: a if a < 0 else 0)(min_list) print(np.sum(upper_count) + np.sum(min_list))