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: Accepted

Solution code:
import sys
input = sys.stdin.readline

N=int(input())
S=tuple(map(int,input().split()))
T=tuple(map(int,input().split()))
U=tuple(map(int,input().split()))
V=tuple(map(int,input().split()))

ANS=[[[-1]*N for i in range(N)] for b in range(64)]

for b in range(64):
    for i in range(N):
        if S[i]==0 and (1<<b) & U[i]!=0:
            for j in range(N):
                if ANS[b][i][j]==0:
                    print(-1)
                    sys.exit()
                ANS[b][i][j]=1

        if S[i]==1 and (1<<b) & U[i]==0:
            for j in range(N):
                if ANS[b][i][j]==1:
                    print(-1)
                    sys.exit()
                ANS[b][i][j]=0


        if T[i]==0 and (1<<b) & V[i]!=0:
            for j in range(N):
                if ANS[b][j][i]==0:
                    print(-1)
                    sys.exit()
                ANS[b][j][i]=1

        if T[i]==1 and (1<<b) & V[i]==0:
            for j in range(N):
                if ANS[b][j][i]==1:
                    print(-1)
                    sys.exit()
                ANS[b][j][i]=0

for rep in range(2):
    for b in range(64):
        for i in range(N):
            if S[i]==0 and (1<<b)& U[i]==0:
                count_mi1=0
                okflag=0
                for j in range(N):
                    if ANS[b][i][j]==0:
                        okflag=1
                        break
                    if ANS[b][i][j]==-1:
                        count_mi1+=1
                        if count_mi1>=2:
                            break
                    
                if okflag==0 and count_mi1==0:
                    print(-1)
                    sys.exit()

                if okflag==0 and count_mi1==1:
                    for j in range(N):
                        if ANS[b][i][j]==-1:
                            ANS[b][i][j]=0
                            break

            if S[i]==1 and (1<<b) & U[i]!=0:
                count_mi1=0
                okflag=0
                for j in range(N):
                    if ANS[b][i][j]==1:
                        okflag=1
                        break
                    if ANS[b][i][j]==-1:
                        count_mi1+=1
                        if count_mi1>=2:
                            break
                    
                if okflag==0 and count_mi1==0:
                    print(-1)
                    sys.exit()

                if okflag==0 and count_mi1==1:
                    for j in range(N):
                        if ANS[b][i][j]==-1:
                            ANS[b][i][j]=1
                            break

            if T[i]==0 and (1<<b)& V[i]==0:
                count_mi1=0
                okflag=0
                for j in range(N):
                    if ANS[b][j][i]==0:
                        okflag=1
                        break
                    if ANS[b][j][i]==-1:
                        count_mi1+=1
                        if count_mi1>=2:
                            break
                    
                if okflag==0 and count_mi1==0:
                    print(-1)
                    sys.exit()

                if okflag==0 and count_mi1==1:
                    for j in range(N):
                        if ANS[b][j][i]==-1:
                            ANS[b][j][i]=0
                            break

            if T[i]==1 and (1<<b) & V[i]!=0:
                count_mi1=0
                okflag=0
                for j in range(N):
                    if ANS[b][j][i]==1:
                        okflag=1
                        break
                    if ANS[b][j][i]==-1:
                        count_mi1+=1
                        if count_mi1>=2:
                            break
                    
                if okflag==0 and count_mi1==0:
                    print(-1)
                    sys.exit()

                if okflag==0 and count_mi1==1:
                    for j in range(N):
                        if ANS[b][j][i]==-1:
                            ANS[b][j][i]=1
                            break

for i in range(N):
    for j in range(N):
        S=[]
        for b in range(63,-1,-1):
            if ANS[b][i][j]==-1:
                S.append((i+j)%2)
            else:
                S.append(ANS[b][i][j])

        print(int("".join(map(str,S)),2),end=" ")
    print()

Submission status: Accepted

Solution code:
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
def resolve():
    N = ir()
    S = lr()
    T = lr()
    U = lr()
    V = lr()
    a = [[0]*N for i in range(N)]
    for k in range(64):
        val = [[bool(U[i]&(1<<k)), bool(V[i]&(1<<k))] for i in range(N)]
        d = [[-1]*N for i in range(N)]
        for i in range(N):
            x = val[i][0]
            if S[i] != x:
                for j in range(N):
                    if d[i][j] != x and d[i][j] != -1:
                        print(-1)
                        return
                    d[i][j] = x
        for j in range(N):
            x = val[j][1]
            if T[j] != x:
                for i in range(N):
                    if d[i][j] != x and d[i][j] != -1:
                        print(-1)
                        return
                    d[i][j] = x
        for _ in range(2):
            for i in range(N):
                x = val[i][0]
                if S[i] == x:
                    p = []
                    ok = False
                    for j in range(N):
                        if d[i][j] == -1:
                            p.append(j)
                        if d[i][j] == x:
                            ok = True
                    if ok:
                        continue
                    if len(p) == 0:
                        print(-1)
                        return
                    if len(p) == 1:
                        d[i][p[0]] = x
            for j in range(N):
                x = val[j][1]
                if T[j] == x:
                    p = []
                    ok = False
                    for i in range(N):
                        if d[i][j] == -1:
                            p.append(i)
                        if d[i][j] == x:
                            ok = True
                    if ok:
                        continue
                    if len(p) == 0:
                        print(-1)
                        return
                    if len(p) == 1:
                        d[p[0]][j] = x
        ni = []
        nj = []
        for i in range(N):
            filled = True
            for j in range(N):
                if d[i][j] == -1:
                    filled = False
                    break
            if not filled:
                ni.append(i)
        for j in range(N):
            filled = True
            for i in range(N):
                if d[i][j] == -1:
                    filled = False
                    break
            if not filled:
                nj.append(j)
        for i, ii in enumerate(ni):
            for j, jj in enumerate(nj):
                d[ii][jj] = (i+j)%2
        for i in range(N):
            for j in range(N):
                a[i][j] |= d[i][j]<<k
    for i in range(N):
        print(*a[i], sep=' ')
resolve()

Submission status: Accepted

Solution code:
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
def resolve():
    N = ir()
    S = lr()
    T = lr()
    U = lr()
    V = lr()
    # d = [[-1]*N for i in range(N)]
    # def flip():
    #     for i in range(N):
    #         for j in range(i):
    #             d[i][j], d[j][i] = d[j][i], d[i][j]
    a = [[0]*N for i in range(N)]
    for k in range(64):
        val = [[bool(U[i]&(1<<k)), bool(V[i]&(1<<k))] for i in range(N)]
        d = [[-1]*N for i in range(N)]
        # for b in range(2):
        for i in range(N):
            x = val[i][0]
            if S[i] != x:
                for j in range(N):
                    if d[i][j] != x and d[i][j] != -1:
                        print(-1)
                        return
                    d[i][j] = x
        for j in range(N):
            x = val[j][1]
            if T[j] != x:
                for i in range(N):
                    if d[i][j] != x and d[i][j] != -1:
                        print(-1)
                        return
                    d[i][j] = x
            # flip()
        for _ in range(2):
            # for b in range(2):
            for i in range(N):
                x = val[i][0]
                if S[i] == x:
                    p = []
                    ok = False
                    for j in range(N):
                        if d[i][j] == -1:
                            p.append(j)
                        if d[i][j] == x:
                            ok = True
                    if ok:
                        continue
                    if len(p) == 0:
                        print(-1)
                        return
                    if len(p) == 1:
                        d[i][p[0]] = x
            for j in range(N):
                x = val[j][1]
                if T[j] == x:
                    p = []
                    ok = False
                    for i in range(N):
                        if d[i][j] == -1:
                            p.append(i)
                        if d[i][j] == x:
                            ok = True
                    if ok:
                        continue
                    if len(p) == 0:
                        print(-1)
                        return
                    if len(p) == 1:
                        d[p[0]][j] = x
                # flip()
        ni = []
        nj = []
        for i in range(N):
            filled = True
            for j in range(N):
                if d[i][j] == -1:
                    filled = False
                    break
            if not filled:
                ni.append(i)
        for j in range(N):
            filled = True
            for i in range(N):
                if d[i][j] == -1:
                    filled = False
                    break
            if not filled:
                nj.append(j)
        for i, ii in enumerate(ni):
            for j, jj in enumerate(nj):
                d[ii][jj] = (i+j)%2
        for i in range(N):
            for j in range(N):
                a[i][j] |= d[i][j]<<k
    for i in range(N):
        print(*a[i], sep=' ')
resolve()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

def main():
    n = int(input())
    ans = [[0 for _ in range(n)] for _ in range(n)]
    s = list(map(int, input().split()))
    t = list(map(int, input().split()))
    u = list(map(int, input().split()))
    v = list(map(int, input().split()))
    for i in range(n):
        if not s[i]:
            for j in range(n):
                ans[i][j] = ans[i][j]|u[i]
        if not t[i]:   
            for j in range(n):
                ans[j][i] = ans[j][i]|v[i]
    for i in range(n):
        for j in range(n):
            if (u[i] & v[j]):
                ans[i][j] = ans[i][j]|(u[i]&v[j])
    for x in range(n):
        if not s[x]:
            continue
        x_sum = ans[x][0]
        for y in range(n):
            x_sum = x_sum|ans[x][y]
        if x_sum == u[x]: 
            continue
        up = u[x] - x_sum
        for y in range(n):
            if t[y]:
                continue
            y_mul = ans[0][y]
            for i in range(n):
                if i == x:
                    continue
                y_mul = y_mul&ans[i][y]
            up_y = (~y_mul)&up
            ans[x][y] += up_y
            up -= up_y
            if not up:
                break
    for y in range(n):
        if not t[y]:
            continue
        y_sum = ans[0][y]
        for x in range(n):
            y_sum = y_sum|ans[x][y]
        if y_sum == v[y]: 
            continue
        up = v[y] - y_sum
        for x in range(n):
            if s[x]:
                continue
            x_mul = ans[x][0]
            for j in range(n):
                if y == j:
                    continue
                x_mul = x_mul&ans[x][j]
            up_x = (~x_mul)&up
            ans[x][y] += up_x
            up -= up_x
            if not up:
                break
    for i in range(n):
        check_xs = ans[i][0]
        check_ys = ans[0][i]
        check_xm = ans[i][0]
        check_ym = ans[0][i]
        for j in range(n):
            check_xs = check_xs|ans[i][j]
            check_ys = check_ys|ans[j][i]
            check_xm = check_xm&ans[i][j]
            check_ym = check_ym&ans[j][i]
        if s[i] and u[i] != check_xs:
            print(-1)
            return       
        if t[i] and v[i] != check_ys:
            print(-1)
            return       
        if not s[i] and u[i] != check_xm:
            print(-1)
            return       
        if not t[i] and v[i] != check_ym:
            print(-1)
            return
    for i in range(n):
        print(*ans[i])

if __name__ == "__main__":
    main()

Submission status: Accepted

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)))
        if can:
            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: Accepted

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 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)

Submission status: Accepted

Solution code:
n,*s=map(int,open(0).read().split());s,t,f,g=[s[i*n:i*n+n]for i in range(4)];r=range(n);a=[n*[0]for _ in r];e=enumerate
for b in range(64):
 y=1<<b;u=[k&y for k in f];v=[k&y for k in g];l=[0]*n;m=l[:]
 for i in r:
  for j in r:
   if(u[i]&v[j])|((s[i]^1)*u[i])|((t[j]^1)*v[j]):a[i][j]|=y;l[i]+=1;m[j]+=1
 for i in r:
  if(l[i]==0)*s[i]*u[i]:
   for j in r:
    if(t[j]^1)*(n-m[j]>1):a[i][j]|=y;m[j]+=1;break
  if(m[i]==0)*t[i]*v[i]:
   for j in r:
    if(s[j]^1)*(n-l[j]>1):a[j][i]|=y;l[j]+=1;break
h=a[0][:];w=[i[0]for i in a]
for i,k in e(a):
 for j,l in e(k):w[i]=(l|w[i]if s[i]else w[i]&l);h[j]=(l|h[j]if t[j]else h[j]&l)
if(g!=h)|(f!=w):print(-1);exit() 
for i in a:print(*i)

Submission status: Accepted

Solution code:
n,*s=map(int,open(0).read().split());s,t,f,g=[s[i*n:i*n+n]for i in range(4)];r=range(n);a=[n*[0]for _ in r];e=enumerate
for b in range(64):
 y=1<<b;u=[k&y for k in f];v=[k&y for k in g];l=[0]*n;m=l[:]
 for i,k in e(u):
  for j,h in e(v):
   if(k&h)|((s[i]^1)*k)|((t[j]^1)*h):a[i][j]|=y;l[i]+=1;m[j]+=1
 for i in r:
  if(l[i]==0)*s[i]*u[i]:
   for j in r:
    if(t[j]^1)*(n-m[j]>1):a[i][j]|=y;m[j]+=1;break
  if(m[i]==0)*t[i]*v[i]:
   for j in r:
    if(s[j]^1)*(n-l[j]>1):a[j][i]|=y;l[j]+=1;break
h=a[0][:];w=[i[0]for i in a]
for i,k in e(a):
 for j,l in e(k):w[i]=(l|w[i]if s[i]else w[i]&l);h[j]=(l|h[j]if t[j]else h[j]&l)
if(g!=h)|(f!=w):print(-1);exit() 
for i in a:print(*i)

Submission status: Accepted

Solution code:
n,*s=map(int,open(0).read().split());s,t,f,g=[s[i*n:i*n+n]for i in range(4)];r=range(n);a=[n*[0]for _ in r];e=1
for _ in[0]*64:
 u=[k&e for k in f];v=[k&e for k in g];l=[0]*n;m=l[:]
 for i in r:
  for j in r:
   if(u[i]&v[j])|((s[i]^1)*u[i])|((t[j]^1)*v[j]):a[i][j]|=e;l[i]+=1;m[j]+=1
 for i in r:
  if(l[i]==0)*s[i]*u[i]:
   for j in r:
    if(t[j]^1)*(n-m[j]>1):a[i][j]|=e;m[j]+=1;break
  if(m[i]==0)*t[i]*v[i]:
   for j in r:
    if(s[j]^1)*(n-l[j]>1):a[j][i]|=e;l[j]+=1;break
 e<<=1
h=a[0][:];w=[i[0]for i in a]
for i in r:
 for j in r:w[i]=(w[i]|a[i][j]if s[i]else w[i]&a[i][j]);h[j]=(h[j]|a[i][j]if t[j]else h[j]&a[i][j])
if(g!=h)|(f!=w):print(-1);exit() 
for i in a:print(*i)

Submission status: Accepted

Solution code:
n,*s=map(int,open(0).read().split());s,t,f,g=[s[i*n:i*n+n]for i in range(4)];r=range(n);a=[n*[0]for _ in r]
for b in range(64):
 e=1<<b;u=[k&e for k in f];v=[k&e for k in g];l=[0]*n;m=l[:]
 for i in r:
  for j in r:
   if(u[i]&v[j])|((s[i]^1)*u[i])|((t[j]^1)*v[j]):a[i][j]|=e;l[i]+=1;m[j]+=1
 for i in r:
  if(l[i]==0)*s[i]*u[i]:
   for j in r:
    if(t[j]^1)*(n-m[j]>1):a[i][j]|=e;m[j]+=1;break
  if(m[i]==0)*t[i]*v[i]:
   for j in r:
    if(s[j]^1)*(n-l[j]>1):a[j][i]|=e;l[j]+=1;break
h=a[0][:];w=[i[0]for i in a]
for i in r:
 for j in r:w[i]=(w[i]|a[i][j]if s[i]else w[i]&a[i][j]);h[j]=(h[j]|a[i][j]if t[j]else h[j]&a[i][j])
if(g!=h)|(f!=w):print(-1);exit() 
for i in a:print(*i)

Submission status: Accepted

Solution code:
n,*s=map(int,open(0).read().split());s,t,f,g=[s[i*n:i*n+n]for i in range(4)];a=[n*[0]for _ in[0]*n];r=range(n)
for b in range(64):
 e=1<<b;u=[k&e for k in f];v=[k&e for k in g];l=[0]*n;m=l[:]
 for i in r:
  for j in r:
   if(u[i]&v[j])|((s[i]^1)*u[i])|((t[j]^1)*v[j]):a[i][j]|=e;l[i]+=1;m[j]+=1
 for i in r:
  if(l[i]==0)*s[i]*u[i]:
   for j in r:
    if(t[j]^1)*(n-m[j]>1):a[i][j]|=e;m[j]+=1;break
 for j in r:
  if(m[j]==0)*t[j]*v[j]:
   for i in r:
    if(s[i]^1)*(n-l[i]>1):a[i][j]|=e;l[i]+=1;break
h=a[0][:];w=[i[0]for i in a]
for i in r:
 for j in r:w[i]=(w[i]|a[i][j]if s[i]else w[i]&a[i][j]);h[j]=(h[j]|a[i][j]if t[j]else h[j]&a[i][j])
if(g!=h)|(f!=w):print(-1);exit() 
for i in a:print(*i)

Submission status: Accepted

Solution code:
#!/usr/bin/python3
import math

def f():
    print(-1)
    exit()

def gen(p, n, s, t, u, v, result):
    a = [ [ -1 for i in range(n) ] for j in range(n) ]
    for i in range(n):
        ub = (u[i] >> p) & 1
        vb = (v[i] >> p) & 1
        if s[i] == 0:
            if ub == 1:
                a[i] = [ 1 for j in range(n) ]
        else:
            if ub == 0:
                a[i] = [ 0 for j in range(n) ]
            
        if t[i] == 0:
            if vb == 1:
                for j in range(n):
                    if a[j][i] == 0:
                        f()
                    a[j][i] = 1
        else:
            if vb == 0:
                for j in range(n):
                    if a[j][i] == 1:
                        f()
                    a[j][i] = 0

    for i in range(n):
        ub = (u[i] >> p) & 1
        if s[i] == 1 and ub == 1:
            if 1 in a[i]:
                continue
            
            for j in range(n):
                vb = (v[j] >> p) & 1
                if t[j] == 1 and vb == 1:
                    a[i][j] = 1
                    break

                if t[j] == 0 and vb == 0:
                    if [ a[k][j] for k in range(n) ].count(1) < n - 1:
                        a[i][j] = 1
                        break;
            else:
                f()

    for i in range(n):
        ub = (u[i] >> p) & 1
        if s[i] == 0 and ub == 0:
            if a[i].count(1) == n:
                f()
                
    for j in range(n):
        vb = (v[j] >> p) & 1
        if t[j] == 1 and vb == 1:
            if 1 in [ a[k][j] for k in range(n) ]:
                continue

            for i in range(n):
                ub = (u[i] >> p) & 1
                if s[i] == 1 and ub == 1:
                    a[i][j] = 1
                    break

                if s[i] == 0 and ub == 0:
                    if a[i].count(1) < n - 1:
                        a[i][j] = 1
                        break
            else:
                f()

    for j in range(n):
        vb = (v[j] >> p) & 1
        if t[j] == 0 and vb == 0:
            if [ a[k][j] for k in range(n) ].count(1) == n:
                fi()
                
    for i in range(n):
        for j in range(n):
            v = a[i][j] if a[i][j] >= 0 else 0
            result[i][j] = result[i][j] | (v << p)

n = int(input())
s = tuple(map(int, input().split()))
t = tuple(map(int, input().split()))
u = tuple(map(int, input().split()))
v = tuple(map(int, input().split()))

p = math.log2(max(u + v))

if p.is_integer():
    p = int(p) + 1
else:
    p = int(math.ceil(p))
    
result = [ [ 0 for i in range(n) ] for j in range(n) ]


for i in range(p):
    gen(i, n, s, t, u, v, result)

for i in range(n):
    print(' '.join(map(str, result[i])))

Submission status: Accepted

Solution code:
from functools import reduce
import operator

N = int(input())
Ss = list(map(int, input().split()))
Ts = list(map(int, input().split()))
Us = list(map(int, input().split()))
Vs = list(map(int, input().split()))
mat = [[0] * N for _ in range(N)]
counts_r = [[0] * 64 for _ in range(N)]
counts_c = [[0] * 64 for _ in range(N)]


class NotOK(Exception):
    pass


try:
    for i in range(N):
        for j in range(N):
            x = 0
            if not Ss[i]:
                x |= Us[i]
            if not Ts[j]:
                x |= Vs[j]
            if Ss[i] and (~Us[i] & x):
                raise NotOK
            if Ts[j] and (~Vs[j] & x):
                raise NotOK
            if Ss[i] and Ts[j]:
                x |= Us[i] & Vs[j]
            mat[i][j] = x
            for k in range(64):
                if (x >> k) & 1:
                    counts_r[i][k] += 1
                    counts_c[j][k] += 1

    def corr(x, vals, ors, counts):
        for k in range(64):
            if (x >> k) & 1 == 0:
                continue
            for j in range(N):
                if ors[j]:
                    continue
                if counts[j][k] >= N - 1:
                    continue
                counts[j][k] += 1
                vals[j] += 1 << k
                x -= 1 << k
                if not x:
                    return x
                break
        return x

    for i in range(N):
        vals = mat[i]
        if Ss[i]:
            x = reduce(operator.or_, vals)
            if corr(Us[i] & ~x, vals, Ts, counts_c):
                raise NotOK
        else:
            x = reduce(operator.and_, vals)
            if x != Us[i]:
                raise NotOK
        vals = []
        for j in range(N):
            vals.append(mat[j][i])
        if Ts[i]:
            x = reduce(operator.or_, vals)
            if corr(Vs[i] & ~x, vals, Ss, counts_r):
                raise NotOK
            for j in range(N):
                mat[j][i] = vals[j]
        else:
            x = reduce(operator.and_, vals)
            if x != Vs[i]:
                raise NotOK
    for i in range(N):
        print(*mat[i])
except NotOK:
    print(-1)