N = int(input()) A_list = [list(map(int, input().split())) for i in range(N)] if N == 1: print(0) exit() upper_count = ([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 = ([([0 for i in range(N)]) for j in range(N - 1)]) minus_list = ([([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] = list(map(sum, zip(add_list[i - 1], add_list[i]))) minus_list[-(i + 1)] = list(map(sum, zip(minus_list[-i], minus_list[-(i + 1)]))) for i in range(len(minus_list) - 1): add_list[i + 1] = list(map(sum, zip(add_list[i + 1], add_list[i]))) minus_list[i + 1] = list(map(sum, zip(minus_list[i + 1], minus_list[i]))) result_list = [0 for i in range(N)] for add, minus in zip(add_list, minus_list): for i in range(N): if add[i] - minus[i] < result_list[i]: result_list[i] = add[i] - minus[i] print(sum(upper_count) + sum(result_list))