Problem:


Score : 600 points

Problem Statement

Given are an integer N and arrays S, T, U, and V, each of length N.
Construct an N×N matrix a that satisfy the following conditions:

a_{i,j} is an integer.

0 \leq a_{i,j}  \lt 2^{64}.

If S_{i} = 0, the bitwise AND of the elements in the i-th row is U_{i}.

If S_{i} = 1, the bitwise OR of the elements in the i-th row is U_{i}.

If T_{i} = 0, the bitwise AND of the elements in the i-th column is V_{i}.

If T_{i} = 1, the bitwise OR of the elements in the i-th column is V_{i}.

However, there may be cases where no matrix satisfies the conditions.

Constraints

All values in input are integers.

 1 \leq N \leq 500 

 0 \leq S_{i} \leq 1 

 0 \leq T_{i} \leq 1  

 0 \leq U_{i} \lt 2^{64}  

 0 \leq V_{i} \lt 2^{64}  

Input

Input is given from Standard Input in the following format:

N
S_{1} S_{2} ...  S_{N}
T_{1} T_{2} ...  T_{N}
U_{1} U_{2} ...  U_{N}
V_{1} V_{2} ...  V_{N}

Output

If there exists a matrix that satisfies the conditions, print one such matrix in the following format:

a_{1,1} ...  a_{1,N}
:
a_{N,1} ...  a_{N,N}

Note that any matrix satisfying the conditions is accepted.

If no matrix satisfies the conditions, print -1.

Sample Input 1

2
0 1
1 0
1 1
1 0

Sample Output 1

1 1
1 0

In Sample Input 1, we need to find a matrix such that:

the bitwise AND of the elements in the 1-st row is 1;

the bitwise OR of the elements in the 2-nd row is 1;

the bitwise OR of the elements in the 1-st column is 1;

the bitwise AND of the elements in the 2-nd column is 0.

Sample Input 2

2
1 1
1 0
15 15
15 11

Sample Output 2

15 11
15 11



Sample input:
2
0 1
1 0
1 1
1 0


Sample output:
1 1
1 0

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
from heapq import heappop, heappush
from itertools import combinations
sys.setrecursionlimit(10**6)
import numpy as np
def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())

    N = int(sysread())
    S = list(map(int, sysread().split()))
    T = list(map(int, sysread().split()))
    U = list(map(int, sysread().split()))
    V = list(map(int, sysread().split()))
    #=================

    #np.random.seed(135)
    #N = 500
    #S = np.random.randint(0, 1, N)
    #T = np.random.randint(0, 1 ,N)
    #U = np.random.randint(1 << 50, 1 << 64, N, dtype=np.uint64)
    #V = np.random.randint(1 << 50, 1 << 64, N, dtype=np.uint64)

    #=================

    Z = [[0] * N for _ in range(N)]
    for i in range(N):
        if not S[i]:
            for k in range(N):
                Z[i][k] |= U[i]
        if not T[i]:
            for k in range(N):
                Z[k][i] |= V[i]

    for i in range(N):
        for j in range(N):
            if S[i] and T[j]:
                Z[i][j] |= U[i]&V[j]
                

            elif S[i] and not T[j]:
                for k in range(N):
                    if k == 0:
                        tmp = Z[1][j]
                    else:
                        tmp = Z[0][j]
                    if k == i:continue
                    tmp &= Z[k][j]
                Z[i][j] |= (tmp ^ U[i]) & U[i]

            elif not S[i] and T[j]:
                for k in range(N):
                    if k == 0:
                        tmp = Z[i][1]
                    else:
                        tmp = Z[i][0]
                    if k == j:continue
                    tmp &= Z[i][k]
                Z[i][j] |= (tmp ^ V[j]) & V[j]

    for i in range(N):
        if S[i]:
            tmp = 0
            for k in range(N):
                tmp |= Z[i][k]
            if tmp != U[i]:
                print(-1)
                return None
        elif not S[i]:
            tmp = Z[i][0]
            for k in range(1,N):
                tmp &= Z[i][k]
            if tmp != U[i]:
                print(-1)
                return None
        if T[i]:
            tmp = 0
            for k in range(N):
                tmp |= Z[k][i]
            if tmp != V[i]:
                print(-1)
                return None
        if not T[i]:
            tmp = Z[0][i]
            for k in range(1,N):
                tmp &= Z[k][i]
            if tmp != V[i]:
                print(-1)
                return None

    for z in Z:
        print(' '.join(list(map(str, z))))




if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
from heapq import heappop, heappush
from itertools import combinations
sys.setrecursionlimit(10**6)
import numpy as np
def run():

    N = int(sysread())
    S = list(map(int, sysread().split()))
    T = list(map(int, sysread().split()))
    U = list(map(int, sysread().split()))
    V = list(map(int, sysread().split()))

    max_n = len(bin(max(U+V))[2:])
    def to_bin(x):
        x = bin(x)[2:]
        return list("0" * (max_n - len(x)) + x)

    U = list(map(to_bin, U))
    V = list(map(to_bin, V))


    Z = np.zeros((N,N), dtype=np.uint64)
    Z_bool = np.zeros((N,N,max_n), dtype = np.int8) - 1

    # fill absolutely determined columns
    row1 = np.array([[False] * max_n for _ in range(N)])
    col1 = np.array([[False] * max_n for _ in range(N)])
    row0 = np.array([[False] * max_n for _ in range(N)])
    col0 = np.array([[False] * max_n for _ in range(N)])
    row1_total = row1.sum(axis=0)
    row0_total = row0.sum(axis=0)
    col1_total = col1.sum(axis=0)
    col0_total = col0.sum(axis=0)

    for i, (s, val) in enumerate(zip(S,U)):
        if s == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[i,:] += 1 << (max_n-idx-1)
                    Z_bool[i,:,idx] = 1
                    row1[i, idx] = True
                    row1_total[idx] = True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z_bool[i, :, idx] = 0
                    row0[i, idx] = True
                    row0_total[idx] += True

    for j, (t, val) in enumerate(zip(T,V)):
        if t == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[:, j] += 1 << (max_n-idx-1)
                    Z_bool[:,j,idx] = 1
                    col1[j, idx] = True
                    col1_total[idx] += True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z_bool[:,j,idx] = 0
                    col0[j, idx] = True
                    col0_total[idx] += True

    for i in range(N):
        for idx in range(max_n):
            if (col1[i,idx] and row0_total[idx]) or (col0[i,idx] and row1_total[idx]) or \
                    (row0[i,idx] and col1_total[idx]) or (row1[i,idx] and col0_total[idx]):
                print(-1)
                return None


    # fill empty columns, according to sum-criteria
    for i, (s, val) in enumerate(zip(S,U)):
        if s == 1:# all 1
            for idx, v in enumerate(val):
                if v == '1':
                    tmp = Z_bool[i, :, idx]
                    if 1 in tmp:continue
                    is_empty = [k for k,_v in enumerate(tmp) if _v==-1]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if T[e] == 0:
                            if 0 in Z_bool[:, e, idx]:
                                Z[i, e] += 1 << (max_n-idx-1)
                                Z_bool[i, e, idx] = 1
                                break
                        else:
                            Z[i, e] += 1 << (max_n - idx-1)
                            Z_bool[i, e, idx] = 1
                            break

    for j, (t, val) in enumerate(zip(T, V)):
        if t == 1:  # all 1
            for idx, v in enumerate(val):
                if v == '1':
                    tmp = Z-bool[:, j, idx]
                    if 1 in tmp: continue
                    is_empty = [k for k,_v in enumerate(tmp) if _v == -1]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if S[e] == 0:
                            if 0 in Z_bool[e, :, idx]:
                                Z[e, j] += 1 << (max_n-idx-1)
                                Z_bool[e,j,idx] = 1
                                break
                        else:
                            Z[e, j] += 1 << (max_n - idx -1)
                            Z_bool[e,j,idx] = 1
                            break

    Z = Z.tolist()

    for z in Z:
        for s in z:
            print("{} ".format(int(s)), end="")
        print("")

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
n = int(input())
s = list(map(int, input().split()))
t = list(map(int, input().split()))
u = list(map(int, input().split()))
v = list(map(int, input().split()))

mat = [[[4]*64 for _ in range(n)] for _ in range(n)]
flag=True

exist1row =[[False]*64 for _ in range(n)]
exist1column = [[False]*64 for _ in range(n)]
exist0row = [[False]*64 for _ in range(n)]
exist0column = [[False]*64 for _ in range(n)]


for k in range(64):
    ambrow=set()
    ambcolumn =set()
    for i in range(n):
        for j in range(n):
            a = (u[i] & 1 << k) >> k
            b = (v[j] & 1 << k) >> k
            if s[i] and t[j]:
                if a == 0 or b == 0:
                    mat[i][j][k]=0
                    exist0row[i][k] =True
                    exist0column[j][k] =True
                else:
                    mat[i][j][k]=2
                    ambrow.add(i)
                    ambcolumn.add(j)
            elif s[i] == 0 and t[j] == 1:
                if a == 1 and b == 0:
                    flag=False
                elif a == 1:
                    mat[i][j][k]=1
                    exist1row[i][k] =True
                    exist1column[j][k] =True
                elif b == 0:
                    mat[i][j][k]=0
                    exist0row[i][k] =True
                    exist0column[j][k] =True
                else:
                    mat[i][j][k]=2
                    ambrow.add(i)
                    ambcolumn.add(j)
            elif s[i] == 1 and t[j] == 0:
                if a == 0 and b == 1:
                    flag=False
                elif a == 0:
                    mat[i][j][k]=0
                    exist0row[i][k] =True
                    exist0column[j][k] =True
                elif b == 1:
                    mat[i][j][k]=1
                    exist1row[i][k] =True
                    exist1column[j][k] =True
                else:
                    mat[i][j][k]=2
                    ambrow.add(i)
                    ambcolumn.add(j)

            else:
                if a == 1 or b == 1:
                    mat[i][j][k]=1
                    exist1row[i][k] =True
                    exist1column[j][k] =True
                else:
                    mat[i][j][k]=2
                    ambrow.add(i)
                    ambcolumn.add(j)

    ambrow = sorted(list(ambrow))
    ambcolumn = sorted(list(ambcolumn))
    if len(ambrow) > 1 and len(ambcolumn) > 1:
        cnti = 0
        for i in ambrow:
            cntj = 0
            for j in ambcolumn:
                mat[i][j][k] = (cnti+cntj)%2
                cntj+=1
            cnti+=1
    elif len(ambrow) == 1:
        i = ambrow[0]
        a = (u[i] & 1 << k) >> k
        for j in ambcolumn:
            b = (v[j] & 1 << k) >> k
            if t[j] == 1:
                assert b == 1
                if not exist1column[j][k]:
                    mat[i][j][k]=1
                    exist1row[i][k] =True
                    exist1column[j][k] =True
            else:
                assert b == 0
                if not exist0column[j][k]:
                    mat[i][j][k]=0
                    exist0row[i][k] =True
                    exist0column[j][k] =True

        if s[i] == 1:
            assert a == 1
            for j in ambcolumn:
                if mat[i][j][k]==2:
                    mat[i][j][k]=1
                    exist1row[i][k] =True
                    exist1column[j][k] =True
            if not exist1row[i][k]:
                flag = false
        else:
            assert a == 0
            for j in ambcolumn:
                if mat[i][j][k]==2:
                    mat[i][j][k]=0
                    exist0row[i][k] =True
                    exist0column[j][k] =True
            if not exist0row[i][k]:
                flag = false
    elif len(ambcolumn) == 1:
        j = ambcolumn[0]
        b = (v[i] & 1 << k) >> k
        for i in ambrow:
            a = (u[j] & 1 << k) >> k
            if s[i] == 1:
                assert a == 1
                if not exist1row[i][k]:
                    mat[i][j][k]=1
                    exist1column[j][k] =True
                    exist1row[i][k] =True
            else:
                assert a == 0
                if not exist0row[i][k]:
                    mat[i][j][k]=0
                    exist0column[j][k] =True
                    exist0row[i][k] =True

        if t[j] == 1:
            assert b == 1
            for i in ambrow:
                if mat[i][j][k]==2:
                    mat[i][j][k]=1
                    exist1column[j][k] =True
                    exist1row[i][k] =True
            if not exist1column[j][k]:
                flag = false
        else:
            assert b == 0
            for i in ambrow:
                if mat[i][j][k]==2:
                    mat[i][j][k]=0
                    exist0column[j][k] =True
                    exist0row[i][k] =True
            if not exist0column[j][k]:
                flag = false

if flag:
    ans = [[0]*n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            for k in range(64):
                ans[i][j]+=mat[i][j][k]<<k

    for i in range(n):
        print(*ans[i])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
from heapq import heappop, heappush
from itertools import combinations
sys.setrecursionlimit(10**6)
import numpy as np
def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())

    N = int(sysread())
    S = list(map(int, sysread().split()))
    T = list(map(int, sysread().split()))
    U = list(map(int, sysread().split()))
    V = list(map(int, sysread().split()))
    #=================
    """
    np.random.seed(135)
    N = 500
    S = np.random.randint(0, 1, N)
    T = np.random.randint(0, 1 ,N)
    U = np.random.randint(0, 1 << 63, N, dtype=np.uint64)
    V = np.random.randint(0, 1 << 63, N, dtype=np.uint64)
    """
    #=================
    max_n = len(bin(max(U+V))[2:])
    def to_bin(x):
        x = bin(x)[2:]
        return list("0" * (max_n - len(x)) + x)

    U = list(map(to_bin, U))
    V = list(map(to_bin, V))


    Z = np.zeros((N,N), dtype=np.uint64)
    Z_bool = np.empty((N,N,max_n))
    Z_bool[:,:,:] = False

    # fill absolutely determined columns
    row1 = np.array([[False] * max_n for _ in range(N)])
    col1 = np.array([[False] * max_n for _ in range(N)])
    row0 = np.array([[False] * max_n for _ in range(N)])
    col0 = np.array([[False] * max_n for _ in range(N)])
    row1_total = row1.sum(axis=0)
    row0_total = row0.sum(axis=0)
    col1_total = col1.sum(axis=0)
    col0_total = col0.sum(axis=0)

    for i, (s, val) in enumerate(zip(S,U)):
        if s == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[i,:] += 1 << (max_n-idx-1)
                    Z_bool[i,:,idx] = True
                    row1[i, idx] = True
                    row1_total[idx] += True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z_bool[i, :, idx] = True
                    row0[i, idx] = True
                    row0_total[idx] += True

    for j, (t, val) in enumerate(zip(T,V)):
        if t == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[:, j] += 1 << (max_n-idx-1)
                    Z_bool[:,j,idx] = True
                    col1[j, idx] = True
                    col1_total[idx] += True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z_bool[:,j,idx] = True
                    col0[j, idx] = True
                    col0_total[idx] += True

    for i in range(N):
        for idx in range(max_n):
            if (col1[i,idx] and row0_total[idx]) or col0[i,idx] and row1_total[idx] or \
                    row0[i,idx] and col1_total[idx] or row1[i,idx] and col0_total[idx]:
                print(-1)
                return None


    # fill empty columns, according to sum-criteria
    for i, (s, val) in enumerate(zip(S,U)):
        if s == 1:# all 1
            for idx, v in enumerate(val):
                if v == '1':
                    if row1[i,idx]:continue
                    is_empty = [k for k,_v in enumerate(Z_bool[i, :, idx]) if not _v]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if T[e] == 0:
                            if col0[e, idx]:
                                Z[i, e] += 1 << (max_n-idx-1)
                                Z_bool[i, e, idx] = True
                                col1[e,idx], row1[i,idx] = True, True
                                break
                        else:
                            Z[i, e] += 1 << (max_n - idx-1)
                            col1[e, idx], row1[i, idx] = True, True
                            Z_bool[i,e,idx] = True

                            break

    for j, (t, val) in enumerate(zip(T, V)):
        if t == 1:  # all 1
            for idx, v in enumerate(val):
                if v == '1':
                    if col1[j,idx]: continue
                    is_empty = [k for k,_v in enumerate(Z_bool[:, j, idx]) if not _v]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if S[e] == 0:
                            if row0[e,idx]:
                                Z[e, j] += 1 << (max_n-idx)
                                row1[e, idx], col1[i, idx] = True, True
                                Z_bool[e,j,idx] = True
                                break
                        else:
                            Z[e, j] += 1 << (max_n - idx)
                            Z_bool[e,j,idx] = True
                            row1[e, idx], col1[i, idx] = True, True
                            break

    Z = Z.tolist()

    for z in Z:
        for s in z:
            print("{} ".format(s), end="")
        print("")

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
from heapq import heappop, heappush
from itertools import combinations
sys.setrecursionlimit(10**6)
import numpy as np
def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())

    N = int(sysread())
    S = list(map(int, sysread().split()))
    T = list(map(int, sysread().split()))
    U = list(map(int, sysread().split()))
    V = list(map(int, sysread().split()))

    max_n = len(bin(max(U+V))[2:])
    def to_bin(x):
        x = bin(x)[2:]
        return "0" * (max_n - len(x)) + x

    U = list(map(to_bin, U))
    V = list(map(to_bin, V))


    Z = (np.zeros((N,N,max_n), dtype=np.int32) - 1)

    # fill absolutely determined columns
    row1 = np.array([[False] * max_n for _ in range(N)])
    col1 = np.array([[False] * max_n for _ in range(N)])
    row0 = np.array([[False] * max_n for _ in range(N)])
    col0 = np.array([[False] * max_n for _ in range(N)])
    row1_total = row1.sum(axis=0)
    row0_total = row0.sum(axis=0)
    col1_total = col1.sum(axis=0)
    col0_total = col0.sum(axis=0)


    for i, (s, val) in enumerate(zip(S,U)):
        if s == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[i, :, idx] = 1
                    row1[i, idx] = True
                    row1_total[idx] += True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z[i, :, idx] = 0
                    row0[i, idx] = True
                    row0_total[idx] += True

    for j, (t, val) in enumerate(zip(T,V)):
        if t == 0:# all 1
            for idx, k in enumerate(val):
                if k=="1":
                    Z[:, j, idx] = 1
                    col1[j, idx] = True
                    col1_total[idx] += True
        else:# all 0
            for idx, k in enumerate(val):
                if k=="0":
                    Z[:, j, idx] = 0
                    col0[j, idx] = True
                    col0_total[idx] += True

    for i in range(N):
        for idx in range(max_n):
            if (col1[i,idx] and row0_total[idx]) or col0[i,idx] and row1_total[idx] or \
                    row0[i,idx] and col1_total[idx] or row1[i,idx] and col0_total[idx]:
                print(-1)
                return None

    # fill empty columns, according to sum-criteria
    for i, (s, val) in enumerate(zip(S,U)):
        if s == 1:# all 1
            for idx, v in enumerate(val):
                if v == '1':
                    if 1 in Z[i, :, idx]:continue
                    is_empty = [k for k,_v in enumerate(Z[i, :, idx]) if _v==-1]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if T[e] == 0:
                            if 0 in Z[:, e, idx]:
                                Z[i, e, idx] = 1
                                break
                        else:
                            Z[i, e, idx] = 1
                            break

    for j, (t, val) in enumerate(zip(T, V)):
        if t == 1:  # all 1
            for idx, v in enumerate(val):
                if v == '1':
                    if 1 in Z[:, j, idx]: continue
                    is_empty = [k for k,_v in enumerate(Z[:, j, idx]) if _v == -1]
                    if is_empty == []:
                        print(-1)
                        return None
                    for e in is_empty:
                        if S[e] == 0:
                            if 0 in Z[e, :, idx]:
                                Z[e, j, idx] = 1
                                break
                        else:
                            Z[e, j, idx] = 1
                            break
    Z[Z==-1] = 0
    Z = Z.astype(str)

    A = [[0] * N for _ in range(N)]

    for i in range(N):
        for j in range(N):
            tmp = str(int(''.join(Z[i,j,:].tolist()), 2))
            A[i][j] = tmp


    for s in A:
        print(' '.join(s))

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env pypy3
import sys
from functools import reduce
from operator import or_, and_


def solve(N: int, S: "List[int]", T: "List[int]", U: "List[int]", V: "List[int]"):
    AND, ORE = 0, 1
    ans = [[0 for j in range(N)] for i in range(N)]
    can = True
    for b in range(64):
        parityU = [(x >> b) & 1 for x in U]
        parityV = [(x >> b) & 1 for x in V]
        can &= all(not (S[i] == ORE and parityU[i] == 0 and T[j] == AND and parityV[j] == 1) for i in range(N) for j in range(N))
        can &= all(not (S[i] == AND and parityU[i] == 1 and T[j] == ORE and parityV[j] == 0) for i in range(N) for j in range(N))
        for i in range(N):
            if S[i] == AND and parityU[i] == 1:
                for j in range(N):
                    ans[i][j] |= 1 << b
        for j in range(N):
            if T[j] == AND and parityV[j] == 1:
                for i in range(N):
                    ans[i][j] |= 1 << b
        rows_free0 = [i for i in range(N) if parityU[i] == 0 or S[i] == ORE and any(x == 1 for x in parityV)]
        rows_free1 = [i for i in range(N) if parityU[i] == 1 or S[i] == AND and any(x == 0 for x in parityV)]
        cols_free0 = [j for j in range(N) if parityV[j] == 0 or T[j] == ORE and any(x == 1 for x in parityU)]
        cols_free1 = [j for j in range(N) if parityV[j] == 1 or T[j] == AND and any(x == 0 for x in parityU)]
        rows_need0 = [i for i in range(N) if S[i] == AND and parityU[i] == 0] if not cols_free0 else []
        rows_need1 = [i for i in range(N) if S[i] == ORE and parityU[i] == 1]
        cols_need0 = [j for j in range(N) if T[j] == AND and parityV[j] == 0] if not rows_free0 else []
        cols_need1 = [j for j in range(N) if T[j] == ORE and parityV[j] == 1]
        if rows_free1:
            for col in cols_need1:
                ans[rows_free1[0]][col] |= 1 << b
            cols_need1 = []
        if cols_free1:
            for row in rows_need1:
                ans[row][cols_free1[0]] |= 1 << b
            rows_need1 = []
        can &= not rows_need0 or any(T[j] == ORE for j in range(N))
        can &= not rows_need1 or any(T[j] == AND for j in range(N))
        can &= not cols_need0 or any(S[i] == ORE for i in range(N))
        can &= not cols_need1 or any(S[i] == AND for i in range(N))
        can &= not any(len(a) == 1 and len(b) > 0 or len(b) == 1 and len(a) > 0 for a, b in ((rows_need0, cols_need1), (rows_need1, cols_need0)))
        for rows, cols in ((rows_need0, cols_need1), (rows_need1, cols_need0)):
            for i in range(max(len(rows), len(cols))):
                ans[rows[i % len(rows)]][cols[i % len(cols)]] |= 1 << b
    if can:
        for row in ans:
            print(*row)
        assert all(reduce(or_ if S[i] else and_, (ans[i][j] for j in range(N))) == U[i] for i in range(N))
        assert all(reduce(or_ if T[j] else and_, (ans[i][j] for i in range(N))) == V[j] for j in range(N))
    else:
        print(-1)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N = int(sys.stdin.readline())  # type: int
    S = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    T = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    U = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    V = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    solve(N, S, T, U, V)

if __name__ == '__main__':
    from time import time
    start = time()
    main()
    end = time()
    print(end - start, file=sys.stderr)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env pypy3
import sys
from functools import reduce
from operator import or_, and_


def solve(N: int, S: "List[int]", T: "List[int]", U: "List[int]", V: "List[int]"):
    AND, ORE = 0, 1
    ans = [[0 for j in range(N)] for i in range(N)]
    can = True
    for b in range(64):
        parityU = [(x >> b) & 1 for x in U]
        parityV = [(x >> b) & 1 for x in V]
        can &= all(not (S[i] == ORE and parityU[i] == 0 and T[j] == AND and parityV[j] == 1) for i in range(N) for j in range(N))
        can &= all(not (S[i] == AND and parityU[i] == 1 and T[j] == ORE and parityV[j] == 0) for i in range(N) for j in range(N))
        for i in range(N):
            if S[i] == AND and parityU[i] == 1:
                for j in range(N):
                    ans[i][j] |= 1 << b
        for j in range(N):
            if T[j] == AND and parityV[j] == 1:
                for i in range(N):
                    ans[i][j] |= 1 << b
        rows_free0 = [i for i in range(N) if parityU[i] == 0 or S[i] == ORE and any(x == 1 for x in parityV)]
        rows_free1 = [i for i in range(N) if parityU[i] == 1 or S[i] == AND and any(x == 0 for x in parityV)]
        cols_free0 = [j for j in range(N) if parityV[j] == 0 or T[j] == ORE and any(x == 1 for x in parityU)]
        cols_free1 = [j for j in range(N) if parityV[j] == 1 or T[j] == AND and any(x == 0 for x in parityU)]
        rows_need0 = [i for i in range(N) if S[i] == AND and parityU[i] == 0] if not cols_free0 else []
        rows_need1 = [i for i in range(N) if S[i] == ORE and parityU[i] == 1]
        cols_need0 = [j for j in range(N) if T[j] == AND and parityV[j] == 0] if not rows_free0 else []
        cols_need1 = [j for j in range(N) if T[j] == ORE and parityV[j] == 1]
        if rows_free1:
            for col in cols_need1:
                ans[rows_free1[0]][col] |= 1 << b
            cols_need1 = []
        if cols_free1:
            for row in rows_need1:
                ans[row][cols_free1[0]] |= 1 << b
            rows_need1 = []
        can &= not rows_need0 or any(T[j] == ORE for j in range(N))
        can &= not rows_need1 or any(T[j] == AND for j in range(N))
        can &= not cols_need0 or any(S[i] == ORE for i in range(N))
        can &= not cols_need1 or any(S[i] == AND for i in range(N))
        can &= not any(len(a) == 1 and len(b) > 0 or len(b) == 1 and len(a) > 0 for a, b in ((rows_need0, cols_need1), (rows_need1, cols_need0)))
        for rows, cols in ((rows_need0, cols_need1), (cols_need0, rows_need1)):
            assert len(rows) == 0 and len(cols) == 0 or len(rows) > 1 and len(cols) > 1
            for ii, i in enumerate(rows):
                for jj, j in enumerate(cols):
                    ans[i][j] |= ((ii & 1) ^ (jj & 1)) << b
    if can:
        for row in ans:
            print(*row)
        # assert all(reduce(or_ if S[i] else and_, (ans[i][j] for j in range(N))) == U[i] for i in range(N))
        # assert all(reduce(or_ if T[j] else and_, (ans[i][j] for i in range(N))) == V[j] for j in range(N))
    else:
        print(-1)


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    N = int(sys.stdin.readline())  # type: int
    S = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    T = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    U = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    V = [int(x) for x in sys.stdin.readline().split()]  # type: "List[int]"
    solve(N, S, T, U, V)

if __name__ == '__main__':
    from time import time
    start = time()
    main()
    end = time()
    print(end - start, file=sys.stderr)