Start of the session (Codeforces 12E)
Tags: Others, constructive algorithms

Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.

Input: The first line contains one integer n (2 ≤ n ≤ 1000), n is even.

Output: Output n lines with n numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any.


Sample Inputs:
2

4

Sample Outputs:
0 1
1 0

0 1 3 2
1 0 2 3
3 2 0 1
2 3 1 0

Solution (Python):
def main():
    n = int(input())
    matrix = [[0 for _ in range(n)] for _ in range(n)]
    for i in range(n):
        for j in range(i + 1):
            if j != i - j:
                matrix[j][i - j] = i
    for i in range(n, 3 * n // 2 - 1):
        for j in range(i - n + 1, n):
            if j != i - j:
                if j == i - n + 1 or j == n - 1:
                    matrix[j][i - j] = (i - n + 1) * 2
                else:
                    matrix[j][i - j] = i - n + 1
    for i in range(3 * n // 2 - 1, n * 2 - 1):
        for j in range(i - n + 1, n):
            if j != i - j:
                if j == i - n + 1 or j == n - 1:
                    matrix[j][i - j] = (i - 3 * n // 2 + 2) * 2 - 1
                else:
                    matrix[j][i - j] = i - n + 1
    for row in matrix:
        print(' '.join(map(str, row)))
if __name__ == '__main__':
    main()

Solution (Python):
__author__ = 'Darren'

def solve():
    n = int(input())
    matrix = [[0] * n for _i in range(n)]
    for i in range(n - 1):
        for j in range(n - 1):
            matrix[i][j] = (i + j) % (n - 1) + 1
    for i in range(n - 1):
        matrix[n - 1][i] = matrix[i][n - 1] = matrix[i][i]
        matrix[i][i] = 0
    for row in matrix:
        print(' '.join(map(str, row)))
if __name__ == '__main__':
    solve()

Solution (Python):
n = int(input())
a = [n - 1] + [k for k in range(1, n)] * 2
for x in range(n - 1):
    row = a[x:x + x] + [0] + a[x + x + 1:n + x - 1] + [a[x + x]]
    print(*row)
print(n - 1, *[a[k * 2] for k in range(1, n - 1)], 0)