Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color a_{k}, i, j; 1 being black and 0 being white. 

Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.


-----Input-----

The first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. 

Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.


-----Output-----

Print one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.


-----Examples-----
Input
1
0

0

1

0

Output
1

Input
3
101
010
101

101
000
101

010
101
011

010
101
010

Output
2

Difficulty: MEDIUM
Tags: Bit manipulation

Implementation

Complete search
Skill types: Bit manipulation

Complete search
Expected Time Complexity: O(N^2)

Starter code:

Solutions:
import sys

def solve(io):
	N = io.readInt()
	boards = [None] * 4
	for i in range(0, 4):
		boards[i] = io.readStringArray(N)
	best = 1234567890
	for v in [((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]:
		best = min(best, delta(boards[v[0][0]], '0') + delta(boards[v[0][1]], '0') + delta(boards[v[1][0]], '1') + delta(boards[v[1][1]], '1'), delta(boards[v[0][0]], '1') + delta(boards[v[0][1]], '1') + delta(boards[v[1][0]], '0') + delta(boards[v[1][1]], '0'))
	io.println(+best)

def delta(b, tl):
	cnt = 0
	for i in range(0, len(b)):
		for j in range(0, len(b[i])):
			if ((i + j) % 2 == 0) != (b[i][j] == tl):
				cnt += 1
	return cnt

class IO:
	input = None
	output = None
	raw = ''
	buf = []
	pos = 0

	def __init__(self, inputStream, outputStream):
		self.input = inputStream
		self.output = outputStream

	def readToBuffer(self):
		self.raw = self.input.readline().rstrip('\n')
		self.buf = self.raw.split()
		self.pos = 0

	def readString(self):
		while self.pos == len(self.buf):
			self.readToBuffer()
		ans = self.buf[self.pos]
		self.pos += 1
		return ans

	def readInt(self):
		return int(self.readString())

	def readFloat(self):
		return float(self.readString())

	def readStringArray(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.readString())
		return arr

	def readIntArray(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.readInt())
		return arr

	def readFloatArray(self, N, offset=0):
		arr = [None] * offset
		for _ in range(0, N):
			arr.append(self.readFloat())
		return arr

	def readLine(self):
		while self.pos == len(self.buf):
			self.readToBuffer()
		if self.pos > 0:
			raise ValueError('Cannot call readline in the middle of a line.')
		return self.raw

	def prints(self, s):
		self.output.write(str(s))

	def println(self, s):
		self.prints(s)
		self.prints('\n')

	def flushOutput(self):
		self.output.flush()
pythonIO = IO(sys.stdin, sys.stdout)
solve(pythonIO)
pythonIO.flushOutput()


n = int(input())
p = []
for i in range(4):
	p1 = []
	if i == 3:
		for j in range(n):
			p1.append(input())
		p.append(p1)
	else:
		for j in range(n):
			p1.append(input())
		w = input()
		p.append(p1)
min_1 = []
min_2 = []
for k in range(4):
	cnt = 0
	for i in range(n):
		for j in range(n):
			if (i + j) % 2 and p[k][i][j] == '1' or ((i + j) % 2 == 0 and p[k][i][j] == '0'):
				cnt += 1
	min_1.append(cnt)
	min_2.append(n * n - cnt)
min_1.sort()
min_2.sort()
print(min_1[0] + min_2[1] + min_1[1] + min_2[0])


from itertools import permutations
n = int(input())
d = []
for i in range(3):
	d.append([list(map(int, input())) for j in range(n)])
	input()
d.append([list(map(int, input())) for j in range(n)])
cache = [[[i * (n * 2 + 1) + j + f & 1 for j in range(n * 2)] for i in range(n * 2)] for f in range(2)]
res = [[a[i] + b[i] for i in range(n)] + [c[i] + e[i] for i in range(n)] for (a, b, c, e) in permutations(d)]
ans = min((sum((resi[i][j] != cache[f][i][j] for j in range(n * 2) for i in range(n * 2))) for f in range(2) for resi in res))
print(ans)


n = int(input())
b1 = [[int(x) for x in input()] for _ in range(n)]
input()
b2 = [[int(x) for x in input()] for _ in range(n)]
input()
b3 = [[int(x) for x in input()] for _ in range(n)]
input()
b4 = [[int(x) for x in input()] for _ in range(n)]

def cost(b):
	z = o = 0
	for i in range(n):
		for j in range(n):
			if (i + j) % 2 == b[i][j]:
				z += 1
			if (i + j + 1) % 2 == b[i][j]:
				o += 1
	return (z, o)
(z1, o1) = cost(b1)
(z2, o2) = cost(b2)
(z3, o3) = cost(b3)
(z4, o4) = cost(b4)
print(min(z1 + z2 + o3 + o4, z1 + o2 + z3 + o4, z1 + o2 + o3 + z4, o1 + z2 + z3 + o4, o1 + z2 + o3 + z4, o1 + o2 + z3 + z4))


n = int(input())
N = [0, 0, 0, 0]
for i in range(4):
	for j in range(n):
		t = input()
		for k in range(n):
			if int(t[k]) == (j + k) % 2:
				N[i] += 1
	if i != 3:
		s = input()
M = [0, 0, 0, 0]
for i in range(4):
	M[i] = n * n - N[i]
L = [0] * 6
L[0] = N[0] + N[1] + M[2] + M[3]
L[1] = N[0] + N[2] + M[1] + M[3]
L[2] = N[0] + N[3] + M[1] + M[2]
L[3] = N[1] + N[2] + M[0] + M[3]
L[4] = N[1] + N[3] + M[0] + M[2]
L[5] = N[2] + N[3] + M[0] + M[1]
mn = L[0]
for i in range(1, 6):
	if L[i] < mn:
		mn = L[i]
print(mn)


n = int(input())
a = [[[0 for j in range(n)] for i in range(n)] for k in range(4)]
in1 = [[0, 0] for i in range(4)]
for k in range(4):
	for i in range(n):
		s = input()
		for j in range(n):
			a[k][i][j] = int(s[j])
			if int(s[j]) == (i + j) % 2:
				in1[k][1] += 1
	in1[k][0] = n * n - in1[k][1]
	if k != 3:
		s = input()
min1 = 10000000000
min1 = min(min1, in1[0][0] + in1[1][0] + in1[2][1] + in1[3][1])
min1 = min(min1, in1[0][0] + in1[1][1] + in1[2][0] + in1[3][1])
min1 = min(min1, in1[0][0] + in1[1][1] + in1[2][1] + in1[3][0])
min1 = min(min1, in1[0][1] + in1[1][1] + in1[2][0] + in1[3][0])
min1 = min(min1, in1[0][1] + in1[1][0] + in1[2][1] + in1[3][0])
min1 = min(min1, in1[0][1] + in1[1][0] + in1[2][0] + in1[3][1])
print(min1)


from itertools import permutations
n = int(input())
(p1, _, p2, _, p3, _, p4) = ([input() for _ in range(n)], input(), [input() for _ in range(n)], input(), [input() for _ in range(n)], input(), [input() for _ in range(n)])

def count(a, b, c, d):
	board = [a[i] + b[i] for i in range(n)] + [c[i] + d[i] for i in range(n)]
	res = 0
	for i in range(2 * n):
		for j in range(2 * n):
			clr = '1' if (i + j) % 2 == 0 else '0'
			res += board[i][j] != clr
	return res
print(min((count(*p) for p in permutations([p1, p2, p3, p4]))))


n = int(input())
a1 = []
for i in range(n):
	a = str(input())
	a = list(a)
	a1.append(a)
x1 = str(input())
a2 = []
for i in range(n):
	a = str(input())
	a = list(a)
	a2.append(a)
x1 = str(input())
a3 = []
for i in range(n):
	a = str(input())
	a = list(a)
	a3.append(a)
x1 = str(input())
a4 = []
for i in range(n):
	a = str(input())
	a = list(a)
	a4.append(a)
ab = []
ab.append(a1)
ab.append(a2)
ab.append(a3)
ab.append(a4)
x = []
one = []
for i in range(n):
	z = []
	for j in range(n):
		if (i + j) % 2 == 0:
			z.append('1')
		else:
			z.append('0')
	one.append(z)
two = []
for i in range(n):
	z = []
	for j in range(n):
		if (i + j) % 2 == 0:
			z.append('0')
		else:
			z.append('1')
	two.append(z)
for i in range(4):
	e1 = 0
	o1 = 0
	for j in range(n):
		for k in range(n):
			if ab[i][j][k] != one[j][k]:
				e1 += 1
			if ab[i][j][k] != two[j][k]:
				o1 += 1
	x.append([e1, o1])
s = x[0][0] + x[1][1] + x[2][0] + x[3][1]
if x[0][0] + x[1][0] + x[2][1] + x[3][1] < s:
	s = x[0][0] + x[1][0] + x[2][1] + x[3][1]
if x[0][0] + x[1][1] + x[2][1] + x[3][0] < s:
	s = x[0][0] + x[1][1] + x[2][1] + x[3][0]
if x[0][1] + x[1][0] + x[2][1] + x[3][0] < s:
	s = x[0][1] + x[1][0] + x[2][1] + x[3][0]
if x[0][1] + x[1][1] + x[2][0] + x[3][0] < s:
	s = x[0][1] + x[1][1] + x[2][0] + x[3][0]
if x[0][1] + x[1][0] + x[2][0] + x[3][1] < s:
	s = x[0][1] + x[1][0] + x[2][0] + x[3][1]
print(s)


from itertools import permutations

def min_cnt(a_):

	def foo(abracadabra, f):
		flag = f
		cnt = 0
		for i in abracadabra:
			ic = i[:]
			for x in range(len(i)):
				flag = not flag
				if flag == i[x]:
					cnt += 1
					ic[x] = not ic[x]
			flag = not ic[0]
		return cnt
	return min(foo(a_, True), foo(a_, False))

def concat(a, b, c, d):
	abcd = []
	for x in (zip(a, b), zip(c, d)):
		x_ = []
		for (i, j) in x:
			x_.append(i + j)
		abcd += x_
	return abcd
n = int(input())
(a, b, c, d) = [list(filter(None, [[y == '1' for y in input()] for x in range(n + (z != 3))])) for z in range(4)]
m = float('inf')
r = None
for (a, b, c, d) in permutations([a, b, c, d]):
	mp = m
	m = min(m, min_cnt(concat(a, b, c, d)))
	if m != mp:
		r = concat(a, b, c, d)
print(m)


def s1(a, b):
	su = 0
	for i in range(len(a)):
		for j in range(len(a)):
			if a[i][j] != b[i][j]:
				su += 1
	return su

def s2(a, b):
	su = 0
	for i in range(len(a)):
		for j in range(len(a)):
			if a[i][j] == b[i][j]:
				su += 1
	return su
n = int(input())
(ideal1, ideal2) = ([], [])
for i in range(n):
	ideal1.append([])
	ideal2.append([])
	for j in range(n):
		if (i + j) % 2 == 0:
			ideal1[i].append(0)
			ideal2[i].append(1)
		else:
			ideal1[i].append(1)
			ideal2[i].append(0)
b = [[], [], [], []]
for i in range(n):
	s = input()
	b[0].append([])
	for j in range(len(s)):
		if s[j] == '0':
			b[0][i].append(0)
		else:
			b[0][i].append(1)
s = input()
for i in range(n):
	s = input()
	b[1].append([])
	for j in range(len(s)):
		if s[j] == '0':
			b[1][i].append(0)
		else:
			b[1][i].append(1)
s = input()
for i in range(n):
	s = input()
	b[2].append([])
	for j in range(len(s)):
		if s[j] == '0':
			b[2][i].append(0)
		else:
			b[2][i].append(1)
s = input()
for i in range(n):
	s = input()
	b[3].append([])
	for j in range(len(s)):
		if s[j] == '0':
			b[3][i].append(0)
		else:
			b[3][i].append(1)
l = []
for i in range(4):
	for j in range(4):
		if i != j:
			c1 = s1(b[i], ideal1) + s1(b[j], ideal1)
			c2 = s1(b[i], ideal2) + s1(b[j], ideal2)
			su1 = c1
			su2 = c2
			for k in range(4):
				if k != i and k != j:
					su1 += s2(b[k], ideal1)
					su2 += s2(b[k], ideal2)
			l.append(min(su1, su2))
print(min(l))


n = int(input())
w = [0, 0, 0, 0]
b = [0, 0, 0, 0]
for i in range(4):
	for count in range(n):
		line = list(map(int, input()))
		for pos in range(n):
			w[i] += abs((count + pos) % 2 - line[pos])
			b[i] += abs(abs((count + pos) % 2 - line[pos]) - 1)
	if i < 3:
		input()
w.sort()
b.sort()
print(w[0] + w[1] + b[0] + b[1])


from itertools import permutations

def solve(TL, TR, BL, BR, s, n):
	A = []
	for i in range(n):
		X = TL[i].copy()
		X.extend(TR[i])
		A.append(X)
	for i in range(n):
		X = BL[i].copy()
		X.extend(BR[i])
		A.append(X)
	c = 0
	ans = 0
	for i in range(2 * n):
		if i % 2 == 1:
			c = s ^ 1
		else:
			c = s
		for j in range(2 * n):
			if A[i][j] != c:
				ans += 1
				A[i][j] = c
			c ^= 1
	return ans
n = int(input())
P = []
for _ in range(4):
	A = []
	for i in range(n):
		A.append(list(map(int, list(input()))))
	if _ != 3:
		input()
	P.append(A)
ans = 4 * n * n + 1
for S in permutations(range(4)):
	for s in range(2):
		cur = solve(P[S[0]], P[S[1]], P[S[2]], P[S[3]], s, n)
		ans = min(ans, cur)
print(ans)


def zero_dis(board, n):
	dis = 0
	for r in range(0, n):
		for c in range(0, n):
			if (r + c) % 2 != int(board[r][c]):
				dis += 1
	return dis

def one_dis(board, n):
	dis = 0
	for r in range(0, n):
		for c in range(0, n):
			if (r + c) % 2 == int(board[r][c]):
				dis += 1
	return dis
while True:
	n = int(input())
	bs = []
	for board in range(0, 4):
		boardy = []
		for row in range(0, n):
			R = input()
			boardy.append(R)
		bs.append(boardy)
		if board != 3:
			input()
	zero_disses = []
	for b in bs:
		zero_disses.append(zero_dis(b, n))
	zero_disses.sort()
	c = zero_disses[0] + zero_disses[1] + 2 * n ** 2 - zero_disses[2] - zero_disses[3]
	print(c)
	break


import math
from decimal import Decimal

def na():
	n = int(input())
	b = [int(x) for x in input().split()]
	return (n, b)

def nab():
	n = int(input())
	b = [int(x) for x in input().split()]
	c = [int(x) for x in input().split()]
	return (n, b, c)

def dv():
	(n, m) = map(int, input().split())
	return (n, m)

def dva():
	(n, m) = map(int, input().split())
	a = [int(x) for x in input().split()]
	b = [int(x) for x in input().split()]
	return (n, m, b)

def eratosthenes(n):
	sieve = list(range(n + 1))
	for i in sieve:
		if i > 1:
			for j in range(i + i, len(sieve), i):
				sieve[j] = 0
	return sorted(set(sieve))

def nm():
	n = int(input())
	b = [int(x) for x in input().split()]
	m = int(input())
	c = [int(x) for x in input().split()]
	return (n, b, m, c)

def dvs():
	n = int(input())
	m = int(input())
	return (n, m)
n = int(input())
d = [0] * 4
for i in range(4):
	for j in range(n):
		s = input()
		for k in range(n):
			if (k + j) % 2 == 0:
				if s[k] == '1':
					d[i] += 1
			elif s[k] == '0':
				d[i] += 1
	if i < 3:
		input()
dop = n * n
d = sorted(d)
ans = dop * 2 + d[0] + d[1] - d[2] - d[3]
print(ans)


n = int(input())
board = [[list(map(int, list(input()))) for i in range(n)]]
for _ in range(3):
	input()
	board.append([list(map(int, list(input()))) for i in range(n)])
var_ = ['1100', '1010', '1001', '0110', '0101', '0011']
ans = 4 * n ** 2
for pat in var_:
	now = 0
	for (ind, ch) in enumerate(list(map(int, list(pat)))):
		b = board[ind]
		for i in range(n):
			for j in range(n):
				if (i + j + ch) % 2 != b[i][j]:
					now += 1
	ans = min(ans, now)
print(ans)


n = int(input())
answer = []
for k in range(4):
	white_problems = 0
	black_problems = 0
	for j in range(n):
		a = [int(i) for i in list(input())]
		for x in range(n):
			if (a[x] == 1 and x % 2 == 0 or (a[x] == 0 and x % 2 == 1)) and j % 2 == 0:
				white_problems += 1
			if (a[x] == 1 and x % 2 == 1 or (a[x] == 0 and x % 2 == 0)) and j % 2 == 0:
				black_problems += 1
			if (a[x] == 1 and x % 2 == 0 or (a[x] == 0 and x % 2 == 1)) and j % 2 == 1:
				black_problems += 1
			if (a[x] == 1 and x % 2 == 1 or (a[x] == 0 and x % 2 == 0)) and j % 2 == 1:
				white_problems += 1
	answer.append([white_problems, 0])
	answer.append([black_problems, 1])
	if k != 3:
		trash = input()
answer.sort()
black = 0
white = 0
ans = 0
for i in answer:
	if black < 2 and i[1] == 1:
		ans += i[0]
		black += 1
		continue
	if white < 2 and i[1] == 0:
		white += 1
		ans += i[0]
		continue
	if white == 2 and black == 2:
		break
print(ans)


a = int(input())
l = []
total = 0
for i in range(4):
	line = ''
	for x in [0] * a:
		line += input()
	l.append(line)
	input() if i != 3 else 0
l = sorted(l, key=lambda i: i[0::2].count('1') + i[1::2].count('0'))[::-1]
for (z, v) in enumerate(l):
	if z < 2:
		for i in range(a ** 2):
			total += v[i] != '0' if i % 2 else v[i] != '1'
	else:
		for i in range(a ** 2):
			total += v[i] != '1' if i % 2 else v[i] != '0'
print(total)


import sys, math, queue, bisect
from itertools import permutations
MOD = 998244353
sys.setrecursionlimit(1000000)

def cost(p, r, s, n):
	c = 0
	for i in range(n):
		for j in range(n):
			if p[i][j] != r[s][j]:
				c += 1
		s = s ^ 1
	return c
n = int(input())
p = [[], [], [], []]
for i in range(4):
	for j in range(n):
		p[i].append(input())
	if i < 3:
		input()
c = [[], []]
for i in range(n):
	c[i & 1].append('0')
	c[i & 1 ^ 1].append('1')
c[0] = ''.join(c[0])
c[1] = ''.join(c[1])
ans = 5 * n * n
for perm in permutations(range(4)):
	(u, v, w, x) = perm
	pc = 0
	pc += cost(p[u], c, 0, n)
	pc += cost(p[v], c, 1, n)
	pc += cost(p[w], c, 1, n)
	pc += cost(p[x], c, 0, n)
	ans = min(ans, pc)
print(ans)


def getDif(l1, l2, n):
	r = 0
	for i in range(len(l1)):
		for j in range(n):
			if l1[i][j] != l2[i][j]:
				r += 1
	return r
n = int(input())
(boards, type1, type2, num_t1, num_t2, res) = ([], [], [], 0, 0, 0)
for i in range(4 * (n + 1) - 1):
	boards.extend([input()])
boards = list(filter(lambda a: a != '', boards))
boards = [boards[x:x + n] for x in range(0, len(boards), n)]
(c, r1, r2) = (0, '', '')
for i in range(n):
	if c % 2 == 0:
		r1 += '1'
		r2 += '0'
	else:
		r1 += '0'
		r2 += '1'
	c += 1
c = 0
for i in range(n):
	if c % 2 == 0:
		type1.append(r1)
		type2.append(r2)
	else:
		type1.append(r2)
		type2.append(r1)
	c += 1
for (index, i) in enumerate(boards):
	if i == type1 and num_t1 < 2:
		num_t1 += 1
		boards.pop(index)
	elif i == type2 and num_t2 < 2:
		num_t2 += 1
		boards.pop(index)
while num_t2 < 2 or num_t1 < 2:
	if num_t1 < 2:
		(dif_min, pos) = (float('inf'), -1)
		for (index, i) in enumerate(boards):
			dif = getDif(i, type1, n)
			if dif < dif_min:
				dif_min = dif
				pos = index
		num_t1 += 1
		res += dif_min
		boards.pop(pos)
	if num_t2 < 2:
		(dif_min, pos) = (float('inf'), -1)
		for (index, i) in enumerate(boards):
			dif = getDif(i, type2, n)
			if dif < dif_min:
				dif_min = dif
				pos = index
		num_t2 += 1
		res += dif_min
		boards.pop(pos)
print(res)


N = int(input())
a = [0, 1] * N
a2 = [1, 0] * N
pt1 = []
pt2 = []
cnt = 0
for j in range(N):
	arr = input()
	for k in range(N):
		if j % 2 == 1 and int(arr[k]) == a2[k]:
			cnt += 1
		elif j % 2 == 0 and int(arr[k]) == a[k]:
			cnt += 1
pt1.append(cnt)
pt2.append(N * N - cnt)
cnt = 0
s = input()
for j in range(N):
	arr = input()
	for k in range(N):
		if j % 2 == 1 and int(arr[k]) == a2[k]:
			cnt += 1
		elif j % 2 == 0 and int(arr[k]) == a[k]:
			cnt += 1
pt1.append(cnt)
pt2.append(N * N - cnt)
s = input()
cnt = 0
for j in range(N):
	arr = input()
	for k in range(N):
		if j % 2 == 1 and int(arr[k]) == a2[k]:
			cnt += 1
		elif j % 2 == 0 and int(arr[k]) == a[k]:
			cnt += 1
pt1.append(cnt)
pt2.append(N * N - cnt)
s = input()
cnt = 0
for j in range(N):
	arr = input()
	for k in range(N):
		if j % 2 == 1 and int(arr[k]) == a2[k]:
			cnt += 1
		elif j % 2 == 0 and int(arr[k]) == a[k]:
			cnt += 1
pt1.append(cnt)
pt2.append(N * N - cnt)
pt1.sort()
pt2.sort()
print(pt1[0] + pt1[1] + pt2[0] + pt2[1])


n = int(input())
vs = [0] * 4
for i in range(4):
	w = v = 0
	for _ in range(n):
		for k in input():
			w ^= 1
			if w == int(k):
				v += 1
	vs[i] = v
	if i < 3:
		input()
base = 2 * n ** 2 + sum(vs)
minv = 4 * n ** 2
for i in range(4):
	for j in range(i + 1, 4):
		minv = min(minv, base - 2 * (vs[i] + vs[j]))
print(minv)


n = int(input())
s1 = ''
s2 = ''
for i in range(0, n):
	s1 += str(i % 2)
	s2 += str((i + 1) % 2)
a = []
for i in range(0, 7):
	b = 0
	if i % 2 == 0:
		for j in range(0, n):
			s = input()
			if j % 2 == 0:
				for k in range(0, n):
					if s1[k] != s[k]:
						b += 1
			else:
				for k in range(0, n):
					if s2[k] != s[k]:
						b += 1
		a.append(b)
		a.append(n * n - b)
	else:
		x = input()
print(min(a[0] + a[2] + a[5] + a[7], a[0] + a[3] + a[4] + a[7], a[0] + a[3] + a[5] + a[6], a[1] + a[2] + a[4] + a[7], a[1] + a[2] + a[5] + a[6], a[1] + a[3] + a[4] + a[6]))


n = int(input())
k = []
for temp in range(4):
	p = []
	for i in range(n):
		l = list(input())
		l = list(map(int, l))
		p.append(l)
	k.append(p)
	if temp < 3:
		input()
a = []
b = []
count = 0
for i in range(n):
	l = []
	o = []
	for j in range(n):
		if count % 2 == 0:
			l.append(0)
			o.append(1)
		else:
			l.append(1)
			o.append(0)
		count += 1
	a.append(l)
	b.append(o)
counta = [0, 0, 0, 0]
countb = [0, 0, 0, 0]
for rr in range(4):
	for i in range(n):
		for j in range(n):
			if k[rr][i][j] != a[i][j]:
				counta[rr] += 1
			if k[rr][i][j] != b[i][j]:
				countb[rr] += 1
f1 = counta[0] + counta[1] + countb[2] + countb[3]
f2 = counta[0] + counta[2] + countb[1] + countb[3]
f3 = counta[0] + counta[3] + countb[2] + countb[1]
f4 = counta[1] + counta[2] + countb[0] + countb[3]
f5 = counta[1] + counta[3] + countb[0] + countb[2]
f6 = counta[2] + counta[3] + countb[0] + countb[1]
print(min(f1, f2, f3, f4, f5, f6))


def main():
	count = int(input())
	value = [0, 0, 0, 0]
	for x in range(4):
		store = 0
		pole = True
		for y in range(count):
			arr = list(input())
			for z in range(count):
				if arr[z] == '1' and pole:
					store += 1
				if arr[z] == '0' and (not pole):
					store += 1
				pole = not pole
		value[x] = store
		if x <= 2:
			y = input()
	mini = value[0] + value[1] + 2 * count * count - (value[2] + value[3])
	for a in range(15):
		hit = 0
		for b in range(4):
			if 1 << b & a:
				hit += 1
		if hit == 2:
			store = 0
			for b in range(4):
				if 1 << b & a:
					store += value[b]
				else:
					store += count * count - value[b]
			mini = min(mini, store)
	print(mini)
main()


n = int(input())
arr = []

def check2(a):
	white = 0
	black = 0
	needwhite = 0
	needblack = 0
	for i in range(len(a)):
		for j in range(len(a[0])):
			if (i + j) % 2 == 0 and a[i][j] == '0':
				white += 1
			elif (i + j) % 2 == 0 and a[i][j] == '1':
				needwhite += 1
			elif (i + j) % 2 == 1 and a[i][j] == '1':
				black += 1
			else:
				needblack += 1
	return min(needwhite + needblack, white + black)
for i in range(4):
	s = []
	for j in range(n):
		s.append(input())
	if i != 3:
		k = input()
	arr.append(s)
answer = 100 * 100 * 4

def check(can):
	s = []
	for i in range(n):
		s.append(arr[can[0]][i] + arr[can[1]][i])
	for i in range(n):
		s.append(arr[can[2]][i] + arr[can[3]][i])
	return check2(s)
for i1 in range(4):
	for i2 in range(4):
		if i1 != i2:
			for i3 in range(4):
				if i3 != i2 and i3 != i1:
					for i4 in range(4):
						if i4 != i3 and i4 != i2 and (i4 != i1):
							answer = min(check([i1, i2, i3, i4]), answer)
print(answer)


n = int(input())
pieces = []
recolors = []
for i in range(4):
	piece = []
	for j in range(n):
		line = input().strip()
		piece.append(line)
	if i != 3:
		input()
	pieces.append(piece)
	cur1 = 0
	for x in range(n):
		for y in range(n):
			cur1 += (x + y + int(piece[x][y])) % 2
	cur2 = 0
	for x in range(n):
		for y in range(n):
			cur2 += (x + y + 1 + int(piece[x][y])) % 2
	recolors.append([cur1, cur2])
mmin = 2 * n * (2 * n)
enums = [[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]], [[1, 2], [0, 3]], [[1, 3], [0, 2]], [[2, 3], [0, 1]]]
for i in range(len(enums)):
	(a, b) = enums[i]
	summ = recolors[a[0]][0] + recolors[a[1]][0] + recolors[b[0]][1] + recolors[b[1]][1]
	mmin = min((mmin, summ))
print(mmin)


rows = int(input())
boards = []
board = ''
for i in range(4 * rows + 3):
	line = input()
	if not line:
		boards.append(board)
		board = ''
	else:
		board += line
boards.append(board)

def difference(board_in, type=0):
	to_return = 0
	for i in board_in:
		to_return += int(i != str(type))
		type = (type + 1) % 2
	return to_return
zero_board_diff = [difference(i, 0) for i in boards]
one_board_diff = [rows ** 2 - i for i in zero_board_diff]
possibilities = []
for i in range(4):
	for j in range(4):
		if i == j:
			continue
		ones = [0, 1, 2, 3]
		ones.remove(i)
		ones.remove(j)
		possibilities.append(zero_board_diff[i] + zero_board_diff[j] + one_board_diff[ones[0]] + one_board_diff[ones[1]])
print(sorted(possibilities)[0])


n = int(input())
import copy
a = {0: [], 1: [], 2: [], 3: []}
for i in range(4):
	for j in range(n):
		a[i].append([int(k) for k in input()])
	if i != 3:
		f = input()
a1 = copy.deepcopy(a[0])
a2 = copy.deepcopy(a[0])
c1 = 1
c2 = 0

def chkdif(l1, l2):
	co = 0
	for i in range(len(l1)):
		for j in range(len(l1[i])):
			if l1[i][j] != l2[i][j]:
				co += 1
	return co
for i in range(n):
	for j in range(n):
		a1[i][j] = c1 % 2
		c1 += 1
an = [[0, 0] for i in range(4)]
for i in range(n):
	for j in range(n):
		a2[i][j] = 1 - a1[i][j]
for i in a:
	an[i][0] = chkdif(a1, a[i])
	an[i][1] = chkdif(a2, a[i])
pa = []
pa.append(an[0][0] + an[1][0] + an[2][1] + an[3][1])
pa.append(an[0][0] + an[1][1] + an[2][0] + an[3][1])
pa.append(an[0][0] + an[1][1] + an[2][1] + an[3][0])
pa.append(an[0][1] + an[1][0] + an[2][0] + an[3][1])
pa.append(an[0][1] + an[1][1] + an[2][0] + an[3][0])
pa.append(an[0][1] + an[1][0] + an[2][1] + an[3][0])
print(min(pa))


import heapq

def doxor(a, b):
	cnt = 0
	for i in range(len(a)):
		for j in range(len(a[0])):
			cnt += a[i][j] ^ b[i][j]
	return cnt
n = int(input())
(a, b) = ([], [])
for i in range(n):
	(ai, bi) = ([], [])
	for j in range(n):
		if i % 2 == 0:
			ai.append(j % 2)
			bi.append(j % 2 ^ 1)
		else:
			ai.append(j % 2 ^ 1)
			bi.append(j % 2)
	a.append(ai)
	b.append(bi)
board = []
board.append([list(map(int, list(input()))) for _ in range(n)])
input()
board.append([list(map(int, list(input()))) for _ in range(n)])
input()
board.append([list(map(int, list(input()))) for _ in range(n)])
input()
board.append([list(map(int, list(input()))) for _ in range(n)])
a_cnts = []
b_cnts = []
for b0 in board:
	heapq.heappush(a_cnts, doxor(b0, a))
	heapq.heappush(b_cnts, doxor(b0, b))
print(heapq.heappop(a_cnts) + heapq.heappop(a_cnts) + heapq.heappop(b_cnts) + heapq.heappop(b_cnts))


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import ceil
mod = 10 ** 9 + 7

def get_original_pieces(x):
	common = (pow(x, 2) - 1) // 2
	first_piece = '10' * common + '1'
	second_piece = '0' + '10' * common
	return [first_piece, second_piece]
for _ in range(1):
	n = int(input())
	pieces = ['' for _ in range(4)]
	original_pieces = get_original_pieces(n)
	i = 0
	for _ in range(3 + n * 4):
		s = input()
		if s:
			pieces[i] += s
		else:
			i += 1
	till = pow(n, 2)
	fp = [[0, i] for i in range(4)]
	sp = [[0, i] for i in range(4)]
	for i in range(4):
		(fpc, spc) = (0, 0)
		for j in range(till):
			if pieces[i][j] != original_pieces[0][j]:
				fpc += 1
			if pieces[i][j] != original_pieces[1][j]:
				spc += 1
		fp[i][0] = fpc
		sp[i][0] = spc
	fp.sort()
	sp.sort()
	ans1 = fp[0][0] + fp[1][0]
	ans2 = sp[0][0] + sp[1][0]
	for i in range(4):
		if sp[i][1] not in [fp[0][1], fp[1][1]]:
			ans1 += sp[i][0]
		if fp[i][1] not in [sp[0][1], sp[1][1]]:
			ans2 += fp[i][0]
	ans = min(ans1, ans2)
	print(ans)


n = int(input().split()[0])

def cnt(p):
	ans = 0
	for i in range(n):
		s = p[i]
		for j in range(n):
			if (i + j) % 2 == int(s[j]):
				ans += 1
	return ans
ans = []
for i in range(4):
	p = []
	while len(p) < n:
		s = input()
		if len(s) == 0:
			continue
		p.append(s)
	ans.append(cnt(p))
ans.sort()
print(ans[0] + ans[1] + n * n - ans[2] + n * n - ans[3])


n = int(input())
need = []
smth = []
for i in range(n):
	s = ''
	for j in range(n):
		if i % 2 == 0:
			if j % 2 == 0:
				s += '1'
			else:
				s += '0'
		elif j % 2 == 1:
			s += '1'
		else:
			s += '0'
	smth.append(s)
need.append(smth)
smth = []
for i in range(n):
	s = ''
	for j in range(n):
		if i % 2 == 0:
			if j % 2 == 0:
				s += '0'
			else:
				s += '1'
		elif j % 2 == 1:
			s += '0'
		else:
			s += '1'
	smth.append(s)
need.append(smth)
kolvo = []
for i in range(4):
	a = []
	now = []
	sum1 = 0
	sum2 = 0
	for j in range(n):
		s = input()
		now.append(s)
	for x in range(len(now)):
		for y in range(len(now[x])):
			if x % 2 == 0:
				if y % 2 == 0 and now[x][y] == '0':
					sum1 += 1
				elif y % 2 == 1 and now[x][y] == '1':
					sum1 += 1
			elif y % 2 == 0 and now[x][y] == '1':
				sum1 += 1
			elif y % 2 == 1 and now[x][y] == '0':
				sum1 += 1
	a.append(sum1)
	for x in range(len(now)):
		for y in range(len(now[x])):
			if x % 2 == 0:
				if y % 2 == 0 and now[x][y] == '1':
					sum2 += 1
				elif y % 2 == 1 and now[x][y] == '0':
					sum2 += 1
			elif y % 2 == 0 and now[x][y] == '0':
				sum2 += 1
			elif y % 2 == 1 and now[x][y] == '1':
				sum2 += 1
	a.append(sum2)
	kolvo.append(a)
	if i != 3:
		s = input()
ans = 10000000000000000000000000000000000000000000000000000000000000000
for i in range(len(kolvo) - 1):
	for j in range(i + 1, len(kolvo)):
		ind = []
		for z in range(len(kolvo)):
			if z != i and z != j:
				ind.append(z)
		x = ind[0]
		y = ind[1]
		if kolvo[i][0] + kolvo[j][0] + kolvo[x][1] + kolvo[y][1] < ans:
			ans = kolvo[i][0] + kolvo[j][0] + kolvo[x][1] + kolvo[y][1]
for i in range(len(kolvo) - 1):
	for j in range(i + 1, len(kolvo)):
		ind = []
		for z in range(len(kolvo)):
			if z != i and z != j:
				ind.append(z)
		x = ind[0]
		y = ind[1]
		if kolvo[i][1] + kolvo[j][1] + kolvo[x][0] + kolvo[y][0] < ans:
			ans = kolvo[i][1] + kolvo[j][1] + kolvo[x][0] + kolvo[y][0]
print(ans)


n = int(input())

def to_change_white_corners(b):
	n = len(b)
	return sum([1 for (i, x) in enumerate(b) if int(x) == i % 2])

def to_change_black_corners(b):
	n = len(b)
	return sum([1 for (i, x) in enumerate(b) if int(x) == (i + 1) % 2])
to_change = []
for i in range(4):
	b = ''
	for _ in range(n):
		b += input()
	to_change.append((to_change_white_corners(b), to_change_black_corners(b)))
	if i != 3:
		input()
min_ = 40000
for (a, b, c, d) in [(2, 3, 0, 1), (1, 3, 0, 2), (1, 2, 0, 3), (0, 3, 1, 2), (0, 2, 1, 3), (0, 1, 2, 3)]:
	min_ = min(min_, to_change[a][0] + to_change[b][0] + to_change[c][1] + to_change[d][1])
print(min_)


from math import ceil, log
n = int(input())
a1 = []
a2 = []
a3 = []
a4 = []
for i in range(n):
	a1.append(list(input()))
input()
for i in range(n):
	a2.append(list(input()))
input()
for i in range(n):
	a3.append(list(input()))
input()
for i in range(n):
	a4.append(list(input()))
tmp1 = tmp2 = 0
for i in range(n):
	for j in range(n):
		if i % 2 == 0 and j % 2 == 0 or (i % 2 == 1 and j % 2 == 1):
			if a1[i][j] == '0':
				tmp1 += 1
			else:
				tmp2 += 1
		elif a1[i][j] == '1':
			tmp1 += 1
		else:
			tmp2 += 1
cost1 = (tmp1, tmp2)
tmp1 = tmp2 = 0
for i in range(n):
	for j in range(n):
		if i % 2 == 0 and j % 2 == 0 or (i % 2 == 1 and j % 2 == 1):
			if a2[i][j] == '0':
				tmp1 += 1
			else:
				tmp2 += 1
		elif a2[i][j] == '1':
			tmp1 += 1
		else:
			tmp2 += 1
cost2 = (tmp1, tmp2)
tmp1 = tmp2 = 0
for i in range(n):
	for j in range(n):
		if i % 2 == 0 and j % 2 == 0 or (i % 2 == 1 and j % 2 == 1):
			if a3[i][j] == '0':
				tmp1 += 1
			else:
				tmp2 += 1
		elif a3[i][j] == '1':
			tmp1 += 1
		else:
			tmp2 += 1
cost3 = (tmp1, tmp2)
tmp1 = tmp2 = 0
for i in range(n):
	for j in range(n):
		if i % 2 == 0 and j % 2 == 0 or (i % 2 == 1 and j % 2 == 1):
			if a4[i][j] == '0':
				tmp1 += 1
			else:
				tmp2 += 1
		elif a4[i][j] == '1':
			tmp1 += 1
		else:
			tmp2 += 1
cost4 = (tmp1, tmp2)
ans = []
ans.append(cost1[0] + cost2[1] + cost3[1] + cost4[0])
ans.append(cost1[0] + cost3[1] + cost4[1] + cost2[0])
ans.append(cost1[0] + cost3[0] + cost4[1] + cost2[1])
ans.append(cost1[1] + cost2[0] + cost3[0] + cost4[1])
ans.append(cost1[1] + cost3[1] + cost4[0] + cost2[0])
ans.append(cost1[1] + cost3[0] + cost4[0] + cost2[1])
print(min(ans))


n = int(input())
if n == 1:
	d = dict()
	d[0] = 0
	d[1] = 0
	for i in range(4):
		x = int(input())
		d[x] += 1
		if i < 3:
			vide = input()
	v = list(d.values())
	print(abs(v[0] - 2))
else:
	ch1 = '01' * (n // 2) + '0'
	ch2 = '10' * (n // 2) + '1'
	c1 = (ch1 + ch2) * (n // 2) + ch1
	c2 = (ch2 + ch1) * (n // 2) + ch2
	d = dict()
	cas1 = 0
	cas2 = 0
	for j in range(4):
		ch = ''
		for i in range(n):
			ch += input()
		if j < 3:
			vide = input()
		com1 = com2 = 0
		for i in range(len(c1)):
			if c1[i] == ch[i]:
				com1 += 1
			else:
				com2 += 1
		if com1 > com2:
			d[ch, j] = [1, n ** 2 - com1]
			cas1 += 1
		else:
			d[ch, j] = [2, n ** 2 - com2]
			cas2 += 1
	v = list(d.keys())
	if cas1 < cas2:
		while cas1 < cas2:
			m = 0
			p = tuple()
			for i in v:
				if d[i][0] == 2:
					if d[i][1] >= m:
						m = d[i][1]
						p = i
			d[p] = [1, n ** 2 - m]
			cas1 += 1
			cas2 -= 1
	elif cas2 < cas1:
		while cas2 < cas1:
			m = 0
			p = tuple()
			for i in v:
				if d[i][0] == 1:
					if d[i][1] >= m:
						m = d[i][1]
						p = i
			d[p] = [2, n ** 2 - d[p][1]]
			cas2 += 1
			cas1 -= 1
	ans = 0
	for i in v:
		ans += d[i][1]
	print(ans)


def generate_board(size, color):
	board = []
	for _ in range(size):
		row = []
		for _ in range(size):
			row.append(color)
			color = 0 if color == 1 else 1
		board.append(row)
	return board

def distance_from(have, need):
	paint = 0
	for (have_row, need_row) in zip(have, need):
		for (h, n) in zip(have_row, need_row):
			if h != n:
				paint += 1
	return paint

def solution(n, pieces):
	white = generate_board(n, 0)
	black = generate_board(n, 1)
	grid = [(distance_from(p, white), distance_from(p, black)) for p in pieces]
	combinations = [[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0], [1, 0, 1, 0], [1, 1, 0, 0]]
	return min((sum((grid[i][c] for (i, c) in enumerate(combo))) for combo in combinations))

def __starting_point():
	n = int(input())
	pieces = []
	for _ in range(4):
		pieces.append(list((list(map(int, input())) for _ in range(n))))
		if _ < 3:
			input()
	print(solution(n, pieces))
__starting_point()


from itertools import combinations

def fn(mtrx):
	w = 0
	b = 0
	n = len(mtrx)
	for i in range(n):
		for j in range(n):
			if (i + j) % 2:
				if mtrx[i][j] == '0':
					w += 1
				else:
					b += 1
			elif mtrx[i][j] == '1':
				w += 1
			else:
				b += 1
	return (w, b)
n = int(input())
ms = []
for i in range(4):
	mtrx = []
	for _ in range(n):
		mtrx.append(list(input()))
	ms.append(mtrx)
	if i < 3:
		input()
costs = list(map(lambda o: fn(o), ms))
combs = list(map(lambda o: list(o), combinations(range(4), 2)))
mc = 40 ** 4
for ws in combs:
	bs = [0, 1, 2, 3]
	for w in ws:
		bs.remove(w)
	mc = min(mc, costs[ws[0]][0] + costs[ws[1]][0] + costs[bs[0]][1] + costs[bs[1]][1])
print(mc)


def gen(n, isw):
	ws = ('0', '1')
	bs = ('1', '0')
	bl = [bs[x % 2] for x in range(n)]
	wl = [ws[x % 2] for x in range(n)]
	if isw:
		ls = (wl, bl)
	else:
		ls = (bl, wl)
	v = []
	for c in range(n):
		v.append(ls[c % 2])
	return v

def comp(f, s):
	x = 0
	n = len(f)
	for c in range(n):
		for d in range(n):
			if f[c][d] != s[c][d]:
				x += 1
	return x
sz = 4

def getmin(v, n):
	w = gen(n, 1)
	b = gen(n, 0)
	bv = []
	for c in range(sz):
		bv.append((comp(b, v[c]), v[c]))
	bv.sort(key=lambda x: x[0])
	wv = []
	for c in range(sz // 2, sz):
		wv.append((comp(w, bv[c][1]), bv[c][1]))
	sm = 0
	for c in range(sz // 2):
		sm += bv[c][0] + wv[c][0]
	return sm
n = int(input())
v = []
for c in range(sz):
	tv = []
	for d in range(n):
		tv.append(list(input()))
	if c < sz - 1:
		input()
	v.append(tv)
print(getmin(v, n))


n = int(input())
c = [0] * 4
for k in range(4):
	for i in range(n):
		s = input()
		for j in range(n):
			if (i + j) % 2 != int(s[j]):
				c[k] += 1
	if k < 3:
		input()
c.sort()
print(c[0] + c[1] + 2 * n * n - c[2] - c[3])


n = int(input())
b = [[] for i in range(4)]
for i in range(4):
	for j in range(n):
		x = [c == '1' for c in input()]
		b[i].append(x)
	if i != 3:
		input()
from itertools import permutations
res = 10000000000.0
for perm in permutations(list(range(4))):
	curr = 0
	for Y in range(2):
		for X in range(2):
			I = Y * 2 + X
			V = b[perm[I]]
			for y in range(0, n):
				for x in range(0, n):
					if V[y][x] != (Y * n + y + X * n + x) % 2:
						curr += 1
	res = min(res, curr)
print(res)


n = int(input())
p = [[[] for _ in range(n)] for _ in range(4)]
for i in range(4):
	for j in range(n):
		r = list(map(int, list(input())))
		p[i][j] = r
	if i < 3:
		input()
dif = [0] * 4
for k in range(4):
	o = 0
	for i in range(n):
		for j in range(n):
			if p[k][i][j] == (n * i + j) % 2:
				o += 1
	dif[k] = (o, n * n - o)
res = 10 ** 19
z = sum((dif[_][1] for _ in range(4)))
for k1 in range(4):
	for k2 in range(k1 + 1, 4):
		res = min(res, dif[k1][0] + dif[k2][0] + z - dif[k1][1] - dif[k2][1])
print(res)


import bisect
import math
import itertools
import sys
alpha = 'abcdefghijklmnopqrstuvwxyz'
inf = 1e+17

def calc1(grid):
	l = len(grid)
	cnt = 0
	for i in range(l):
		for j in range(l):
			if (i + j) % 2 and grid[i][j]:
				cnt += 1
			if (i + j) % 2 == 0 and grid[i][j] == 0:
				cnt += 1
	return cnt

def calc2(grid):
	l = len(grid)
	cnt = 0
	for i in range(l):
		for j in range(l):
			if (i + j) % 2 and grid[i][j] == 0:
				cnt += 1
			if (i + j) % 2 == 0 and grid[i][j]:
				cnt += 1
	return cnt

def solve(n, grids):
	one = []
	zero = []
	for grid in grids:
		one.append(calc1(grid))
		zero.append(calc2(grid))
	take = [3, 5, 6, 9, 10, 12]
	answer = inf
	for mask in range(16):
		cnt = 0
		if mask not in take:
			continue
		if mask in take:
			if mask & 1:
				cnt += one[3]
				pass
			else:
				cnt += zero[3]
				pass
			if mask & 2:
				cnt += one[2]
				pass
			else:
				cnt += zero[2]
				pass
			if mask & 4:
				cnt += one[1]
				pass
			else:
				cnt += zero[1]
				pass
			if mask & 8:
				cnt += one[0]
				pass
			else:
				cnt += zero[0]
				pass
		answer = min(answer, cnt)
	return answer
t = 1
ans = []
for _ in range(t):
	n = int(input())
	grids = []
	for i in range(4):
		grid = []
		for j in range(n):
			arr = list(map(int, list(input())))
			grid.append(arr)
		if i != 3:
			s = input()
		grids.append(grid)
	ans.append(solve(n, grids))
for test in ans:
	print(test)


n = int(input())
row1 = [0, 1] * (n // 2) + [0]
row2 = [1, 0] * (n // 2) + [1]
d = []
for i in range(4):
	d.append([0, 0])
	for j in range(n):
		row = [int(x) for x in input()]
		for k in range(n):
			if j % 2 == 0:
				d[i][0] += abs(row1[k] - row[k])
				d[i][1] += abs(row2[k] - row[k])
			else:
				d[i][1] += abs(row1[k] - row[k])
				d[i][0] += abs(row2[k] - row[k])
	if i < 3:
		input()
m = [0] * 6
m[0] = d[0][0] + d[1][0] + d[2][1] + d[3][1]
m[1] = d[0][0] + d[1][1] + d[2][0] + d[3][1]
m[2] = d[0][0] + d[1][1] + d[2][1] + d[3][0]
m[3] = d[0][1] + d[1][0] + d[2][0] + d[3][1]
m[4] = d[0][1] + d[1][0] + d[2][1] + d[3][0]
m[5] = d[0][1] + d[1][1] + d[2][0] + d[3][0]
print(min(m))


import itertools
n = int(input())
boards = []
for i in range(4):
	boards.append([])
	for j in range(n):
		boards[-1].append(list(map(int, list(input()))))
	if i < 3:
		input()
ans = n * n * 4

def check_board(corner, board):
	ans = 0
	for i in range(n):
		for j in range(n):
			if board[i][j] != corner:
				ans += 1
			corner = 1 - corner
	return ans

def solve(corner, p):
	ans = check_board(corner, boards[p[0]])
	ans += check_board(1 - corner, boards[p[1]])
	ans += check_board(1 - corner, boards[p[2]])
	ans += check_board(corner, boards[p[3]])
	return ans
for p in itertools.permutations(range(4), 4):
	ans = min(ans, solve(1, p))
	ans = min(ans, solve(0, p))
print(ans)


n = int(input())
parts = []
for _ in range(4):
	p = ''
	for r in range(n):
		p += input()
	parts.append(p)
	if _ != 3:
		input()
op1 = '10' * (1 + n ** 2 // 2)
op2 = '01' * (1 + n ** 2 // 2)
op1 = op1[:n ** 2]
op2 = op2[:n ** 2]
cases = [((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2)), ((1, 2), (0, 3)), ((1, 3), (0, 2)), ((2, 3), (0, 1))]
total = 4 * n ** 2
current = 0
for (c1, c2) in cases:
	(a1, a2) = (parts[c1[0]], parts[c1[1]])
	(a3, a4) = (parts[c2[0]], parts[c2[1]])
	current += sum((c != c_1 for (c, c_1) in zip(op1, a1)))
	current += sum((c != c_1 for (c, c_1) in zip(op1, a2)))
	current += sum((c != c_2 for (c, c_2) in zip(op2, a3)))
	current += sum((c != c_2 for (c, c_2) in zip(op2, a4)))
	total = min(current, total)
	current = 0
print(total)


n = int(input())
lst1 = []
for x in range(n):
	lst1.append(input().split())
s = input()
lst2 = []
for x in range(n):
	lst2.append(input().split())
s = input()
lst3 = []
for x in range(n):
	lst3.append(input().split())
s = input()
lst4 = []
for x in range(n):
	lst4.append(input().split())
ans_b1 = 0
ans_w1 = 0
for x in range(n):
	for y in range(n):
		if x + y & 1 == 0:
			if lst1[x][0][y] == '0':
				ans_b1 += 1
			else:
				ans_w1 += 1
		elif lst1[x][0][y] == '1':
			ans_b1 += 1
		else:
			ans_w1 += 1
ans_b2 = 0
ans_w2 = 0
for x in range(n):
	for y in range(n):
		if x + y & 1 == 0:
			if lst2[x][0][y] == '0':
				ans_b2 += 1
			else:
				ans_w2 += 1
		elif lst2[x][0][y] == '1':
			ans_b2 += 1
		else:
			ans_w2 += 1
ans_b3 = 0
ans_w3 = 0
for x in range(n):
	for y in range(n):
		if x + y & 1 == 0:
			if lst3[x][0][y] == '0':
				ans_b3 += 1
			else:
				ans_w3 += 1
		elif lst3[x][0][y] == '1':
			ans_b3 += 1
		else:
			ans_w3 += 1
ans_b4 = 0
ans_w4 = 0
for x in range(n):
	for y in range(n):
		if x + y & 1 == 0:
			if lst4[x][0][y] == '0':
				ans_b4 += 1
			else:
				ans_w4 += 1
		elif lst4[x][0][y] == '1':
			ans_b4 += 1
		else:
			ans_w4 += 1
print((2 * n) ** 2 - max(ans_b1 + ans_b2 + ans_w3 + ans_w4, ans_b1 + ans_w2 + ans_b3 + ans_w4, ans_b1 + ans_w2 + ans_w3 + ans_b4, ans_w1 + ans_b2 + ans_b3 + ans_w4, ans_w1 + ans_b2 + ans_w3 + ans_b4, ans_w1 + ans_w2 + ans_b3 + ans_b4))


import itertools as it

def board_to_color_costs(board):
	(a, b) = (0, 0)
	n = len(board)
	for i in range(n):
		for j in range(n):
			if (i + j) % 2 == 0:
				if board[i][j] == '1':
					a += 1
			elif board[i][j] == '0':
				a += 1
	for i in range(n):
		for j in range(n):
			if (i + j) % 2 == 0:
				if board[i][j] == '0':
					b += 1
			elif board[i][j] == '1':
				b += 1
	return (a, b)
n = int(input())
board_costs = []
for board_index in range(4):
	board = []
	for _ in range(n):
		board += [input()]
	if board_index != 3:
		input()
	board_costs += [board_to_color_costs(board)]
best = (2 * n) ** 2
for perm in it.permutations(board_costs):
	best = min([best, perm[0][0] + perm[1][1] + perm[2][1] + perm[3][0]])
print(best)


n = int(input())
s1 = []
for i in range(n):
	s1.append(list(map(int, input())))
input()
s2 = []
for i in range(n):
	s2.append(list(map(int, input())))
input()
s3 = []
for i in range(n):
	s3.append(list(map(int, input())))
input()
s4 = []
for i in range(n):
	s4.append(list(map(int, input())))
a = [s1, s2, s3, s4]
b = [0, 1, 2, 3]
m = float('inf')
for i in range(4):
	b = [0, 1, 2, 3]
	f = []
	f.append(b[i])
	b.pop(i)
	for j in range(3):
		d = b[:]
		f.append(d[j])
		d.pop(j)
		for k in range(2):
			e = d[:]
			f.append(e[k])
			e.pop(k)
			f.append(e[0])
			se = []
			for v in f:
				se.append(a[v])
			fa = 0
			if n % 2 == 0:
				for seg in se:
					for ii in range(n):
						for jj in range(n):
							if (ii + jj) % 2 != seg[ii][jj]:
								fa += 1
				m = min(m, fa, 4 * n * n - fa)
			else:
				for seg in se[:2]:
					for ii in range(n):
						for jj in range(n):
							if (ii + jj) % 2 != seg[ii][jj]:
								fa += 1
				for seg in se[2:]:
					for ii in range(n):
						for jj in range(n):
							if (ii + jj) % 2 == seg[ii][jj]:
								fa += 1
				m = min(m, fa, 4 * n * n - fa)
			f.pop()
			f.pop()
		f.pop()
	f.pop()
print(m)


n = int(input())
l = []
for i in range(4):
	l.append(0)
for q in range(4):
	for i in range(1, n + 1):
		s = input()
		for j in range(1, n + 1):
			if i % 2 == j % 2 and s[j - 1] == '1':
				l[q] += 1
			if i % 2 != j % 2 and s[j - 1] == '0':
				l[q] += 1
	if q < 3:
		z = input()
l.sort()
n2 = n ** 2
count = 0
count += l[0] + l[1]
count += 2 * n2 - l[2] - l[3]
print(count)


import sys
try:

	def check(n):
		count1 = 0
		s = ''
		while n != 0:
			if n % 2:
				count1 += 1
				s = '1' + s
			else:
				s = '0' + s
			n //= 2
		return s

	def solve(flag, n, l):
		temp_ans = 0
		for i in range(n):
			y = z[flag] ^ int(l[i], 2)
			b = bin(y)
			temp_ans += b.count('1')
			flag = not flag
		return temp_ans
	n = int(input())
	l1 = [input() for y in range(n)]
	temp = input()
	l2 = [input() for y in range(n)]
	temp = input()
	l3 = [input() for y in range(n)]
	temp = input()
	l4 = [input() for y in range(n)]
	z = []
	s = 0
	for i in range(n):
		if i % 2 == 1:
			s += 2 ** i
	z.append(s)
	z.append(z[0] ^ 2 ** n - 1)
	ans = m = sys.maxsize
	for i in range(2, 17):
		s = check(i)
		if s.count('1') == 2:
			s = (4 - len(s)) * '0' + s
			res = sys.maxsize
			for i in range(4):
				if i == 0:
					x = l1
				elif i == 1:
					x = l2
				elif i == 2:
					x = l3
				else:
					x = l4
				if s[i] == '1':
					res += min(res, solve(1, n, x))
				else:
					res += min(res, solve(0, n, x))
			ans = min(ans, res - m)
	print(ans)
except EOFError:
	pass


n = int(input())
parts = []
for i in range(4):
	part = []
	for _i in range(n):
		part.append([int(x) for x in input()])
	parts.append(part)
	if i < 3:
		input()
processed_parts = []
for part in parts:
	dt1 = 0
	exp = 1
	for h in range(n):
		for w in range(n):
			if part[h][w] != exp:
				dt1 += 1
			exp = (exp + 1) % 2
	dt2 = 0
	for h in range(n):
		for w in range(n):
			if part[h][w] != exp:
				dt2 += 1
			exp = (exp + 1) % 2
	processed_parts.append([dt1, dt2])
ans = n * n * 4
for i in range(3):
	for j in range(i + 1, 4):
		a = 0
		for (k, part) in enumerate(processed_parts):
			if k == i or k == j:
				a += part[0]
			else:
				a += part[1]
		ans = min(ans, a)
print(ans)


import sys
n = int(input())
M = [['0' for k in range(n)] for _ in range(n)]
L = [['0' for k in range(n)] for _ in range(n)]
for i in range(n):
	for j in range(n):
		if j % 2 == i % 2:
			M[i][j] = '1'
for i in range(n):
	for j in range(n):
		if j % 2 != i % 2:
			L[i][j] = '1'

def test(K):
	m = 0
	for i in range(n):
		for j in range(n):
			if M[i][j] != K[i][j]:
				m += 1
	return m
A = []
for _ in range(4):
	K = []
	for i in range(n):
		K.append(list(input()))
	f = sys.stdin.readline()
	A.append(test(K))
mini = 100000
a = min(A[0] + A[1] + 2 * n * n - A[2] - A[3], A[0] + A[2] + 2 * n * n - A[1] - A[3], A[0] + A[3] + 2 * n * n - A[2] - A[1])
b = min(A[1] + A[2] + 2 * n * n - A[0] - A[3], A[1] + A[3] + 2 * n * n - A[2] - A[0])
c = A[2] + A[3] + 2 * n * n - A[1] - A[0]
mini = min(a, b, c)
print(mini)


n = int(input())
odd = [0, 0, 0, 0]
for i in range(4):
	even = 0
	for j in range(n):
		a = input()
		for k in range(n):
			if (k + j) % 2 == 0:
				odd[i] += int(a[k])
			else:
				even += int(a[k])
	odd[i] = abs(odd[i] - (n * n + 1) // 2) + even
	if i != 3:
		input()
o = 0
for i in range(2):
	a = max(odd)
	o += n * n - a
	odd.remove(a)
print(sum(odd) + o)


n = int(input())
a = []
b = []
ans = 1000000
for i in range(4):
	a.append([] * n)
	for j in range(n):
		a[i].append([0] * n)
for i in range(4):
	for j in range(n):
		s = input()
		for k in range(len(s)):
			a[i][j][k] = int(s[k])
	if i < 3:
		input()
for i in range(16):
	c = [0] * 4
	y = 3
	ans1 = 0
	while i > 0:
		c[y] = i % 2
		y -= 1
		i //= 2
	c.reverse()
	if sum(c) == 2:
		for k in range(4):
			if c[k] == 1:
				for i in range(n):
					for j in range(n):
						if i % 2 == j % 2:
							ans1 += min(1, 1 - a[k][i][j])
						else:
							ans1 += max(0, a[k][i][j])
			else:
				for i in range(n):
					for j in range(n):
						if i % 2 != j % 2:
							ans1 += min(1, 1 - a[k][i][j])
						else:
							ans1 += max(0, a[k][i][j])
		ans = min(ans, ans1)
print(ans)


n = int(input())
pieces = []
blacks = [0] * 4
whites = [0] * 4
for i in range(4):
	grid = []
	for j in range(n):
		grid.append(input())
	if i < 3:
		input()
	count = 0
	for j in range(n):
		for k in range(n):
			if (int(grid[j][k]) + j + k) % 2:
				count += 1
	blacks[i] = count
	whites[i] = n * n - count
ans = 4 * n * n
for white1 in range(3):
	for white2 in range(white1 + 1, 4):
		for black1 in range(4):
			if black1 == white1 or black1 == white2:
				continue
			for black2 in range(black1 + 1, 4):
				if black2 == white1 or black2 == white2:
					continue
				ans = min(ans, whites[white1] + whites[white2] + blacks[black1] + blacks[black2])
print(ans)


import itertools
n = int(input())
a = []
for i in range(4):
	a.append([input() for _ in range(n)])
	if i < 3:
		assert input() == ''
best = 4 * n * n
for p in itertools.permutations(a):
	for s in range(2):
		count = 0
		for i in range(4):
			for r in range(n):
				for c in range(n):
					if p[i][r][c] != str((s + (i // 2 + r) + (i % 2 + c)) % 2):
						count += 1
		best = min(best, count)
print(best)


from itertools import permutations
n = int(input())
boards = []
for i in range(4):
	board = [input() for j in range(n)]
	boards.append(board)
	if i != 3:
		input()
perms = list(permutations(list(range(4))))

def cost(board):
	base1 = [1, 0] * (len(board) // 2)
	base2 = [0, 1] * (len(board) // 2)
	board1 = []
	board2 = []
	for i in range(len(board) // 2):
		board1.append(base1)
		board1.append(base2)
		board2.append(base2)
		board2.append(base1)
	board = [list(map(int, list(a))) for a in board]
	curr_min_cost1 = 0
	curr_min_cost2 = 0
	for i in range(len(board)):
		for j in range(len(board)):
			curr_min_cost1 += board[i][j] ^ board1[i][j]
			curr_min_cost2 += board[i][j] ^ board2[i][j]
	return min(curr_min_cost1, curr_min_cost2)
min_cost = float('inf')
for p in perms:
	b1 = boards[p[0]] + boards[p[1]]
	b2 = boards[p[2]] + boards[p[3]]
	b = [a + b for (a, b) in zip(b1, b2)]
	min_cost = min(min_cost, cost(b))
print(min_cost)


def f(M):
	N = len(M[0])
	cost0 = 0
	cost1 = 0
	for i in range(N):
		for j in range(N):
			if (i + j) % 2 == 0:
				if M[i][j] != 0:
					cost0 += 1
				else:
					cost1 += 1
			elif M[i][j] != 1:
				cost0 += 1
			else:
				cost1 += 1
	return (cost0, cost1)
n = int(input())
(a, b) = ([[0 for i in range(n)] for j in range(n)], [[0 for i in range(n)] for j in range(n)])
(c, d) = ([[0 for i in range(n)] for j in range(n)], [[0 for i in range(n)] for j in range(n)])
for i in range(n):
	a[i] = list(map(int, list(input())))
blank = input()
for i in range(n):
	b[i] = list(map(int, list(input())))
blank = input()
for i in range(n):
	c[i] = list(map(int, list(input())))
blank = input()
for i in range(n):
	d[i] = list(map(int, list(input())))

def cost(l):
	s = f(l[0])[0] + f(l[1])[1] + f(l[2])[1] + f(l[3])[0]
	n = len(l[0][0])
	return min(s, 4 * n * n - s)
l1 = cost([a, b, c, d])
l2 = cost([a, b, d, c])
l3 = cost([a, c, b, d])
l4 = cost([a, c, d, b])
l5 = cost([a, d, b, c])
l6 = cost([a, d, c, b])
l7 = cost([b, a, c, d])
l8 = cost([b, a, d, c])
l9 = cost([b, c, a, d])
l10 = cost([b, c, d, a])
l11 = cost([b, d, a, c])
l12 = cost([b, d, c, a])
l13 = cost([c, a, b, d])
l14 = cost([c, a, d, b])
l15 = cost([c, b, a, d])
l16 = cost([c, b, d, a])
l17 = cost([c, d, a, b])
l18 = cost([c, d, b, a])
l19 = cost([d, a, b, c])
l20 = cost([d, a, c, b])
l21 = cost([d, b, a, c])
l22 = cost([d, b, c, a])
l23 = cost([d, c, a, b])
l24 = cost([d, c, b, a])
m = min(l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24)
print(m)


n = int(input())
a1 = [[(i + n * j) % 2 for i in range(n)] for j in range(n)]
b1 = [[abs((i + n * j) % 2 - 1) for i in range(n)] for j in range(n)]
cell1 = [list(map(int, list(input()))) for i in range(n)]
l = input()
cell2 = [list(map(int, list(input()))) for i in range(n)]
l = input()
cell3 = [list(map(int, list(input()))) for i in range(n)]
l = input()
cell4 = [list(map(int, list(input()))) for i in range(n)]
count = [[0, 0] for i in range(4)]
for i in range(n):
	for j in range(n):
		if cell1[i][j] != a1[i][j]:
			count[0][0] += 1
		if cell1[i][j] != b1[i][j]:
			count[0][1] += 1
		if cell2[i][j] != a1[i][j]:
			count[1][0] += 1
		if cell2[i][j] != b1[i][j]:
			count[1][1] += 1
		if cell3[i][j] != a1[i][j]:
			count[2][0] += 1
		if cell3[i][j] != b1[i][j]:
			count[2][1] += 1
		if cell4[i][j] != a1[i][j]:
			count[3][0] += 1
		if cell4[i][j] != b1[i][j]:
			count[3][1] += 1
min_1 = min(count[0][0] + count[1][0] + count[2][1] + count[3][1], count[0][0] + count[1][1] + count[2][0] + count[3][1], count[0][1] + count[1][0] + count[2][0] + count[3][1], count[0][0] + count[1][1] + count[2][1] + count[3][0], count[0][1] + count[1][0] + count[2][1] + count[3][0], count[0][1] + count[1][1] + count[2][0] + count[3][0])
print(min_1)


n = int(input())
a = []
for c in range(4):
	q = []
	for i in range(n):
		q.append(input())
	a.append(q)
	if c != 3:
		s = input()
ans = 10 ** 9
for k in range(6):
	if k == 0:
		a0 = [1, 2]
		a1 = [3, 4]
	elif k == 1:
		a0 = [1, 3]
		a1 = [2, 4]
	elif k == 2:
		a0 = [1, 4]
		a1 = [2, 3]
	elif k == 3:
		a0 = [2, 3]
		a1 = [1, 4]
	elif k == 4:
		a0 = [2, 4]
		a1 = [1, 3]
	elif k == 5:
		a0 = [3, 4]
		a1 = [1, 2]
	count = 0
	for i in range(1, 5):
		for x in range(n):
			for y in range(n):
				if i in a0:
					if (x + y) % 2 == 0 and a[i - 1][x][y] == '1':
						count += 1
					elif (x + y) % 2 == 1 and a[i - 1][x][y] == '0':
						count += 1
				elif (x + y) % 2 == 0 and a[i - 1][x][y] == '0':
					count += 1
				elif (x + y) % 2 == 1 and a[i - 1][x][y] == '1':
					count += 1
	ans = min(ans, count)
print(ans)


n = int(input())
aa = [0] * 4
for i in range(4):
	aa[i] = ''.join((input() for j in range(n)))
	if i != 3:
		input()
x = ''.join(('10' for i in range(n ** 2 // 2))) + '1'
y = ''.join(('01' for i in range(n ** 2 // 2))) + '0'
x = int(x, 2)
y = int(y, 2)
a = [0] * 4
b = [0] * 4
for i in range(4):
	a[i] = bin(x ^ int(aa[i], 2))[2:].count('1')
	b[i] = bin(y ^ int(aa[i], 2))[2:].count('1')
ans = [a[0] + a[1] + b[2] + b[3], a[0] + a[2] + b[1] + b[3], a[0] + a[3] + b[2] + b[1], a[1] + a[2] + b[0] + b[3], a[1] + a[3] + b[0] + b[2], a[2] + a[3] + b[0] + b[1]]
print(min(ans))


import sys
n = int(input())

def read_board(n, numb):
	board = []
	for i in range(n):
		line = input()
		board.append([int(c) for c in line])
	if numb != 3:
		input()
	return board
boards = [read_board(n, i) for i in range(4)]

def _calc_line(l, start=1):
	cur = start
	errors = 0
	for cell in l:
		errors += cell != cur
		cur = not cur
	return errors

def _calc_board(b, start=1):
	errors = 0
	cur = start
	for line in b:
		errors += _calc_line(line, cur)
		cur = not cur
	return errors
checks = [(0, 0, 1, 1), (0, 1, 0, 1), (1, 0, 0, 1), (0, 1, 1, 0), (1, 0, 1, 0), (1, 1, 0, 0)]

def check_all(boards):
	for check in checks:
		errs = 0
		for (board, start) in zip(boards, check):
			errs += _calc_board(board, start)
		yield errs
print(min(check_all(boards)))


def read_data():
	n = int(input().strip())
	pieces = []
	for j in range(4):
		a = []
		for i in range(n):
			a.append(input().strip())
		if j < 3:
			input().strip()
		pieces.append(a)
	return (n, pieces)

def solve():
	counts = []
	for piece in pieces:
		cur = 0
		sum = 0
		for i in range(n):
			for j in range(n):
				if ord(piece[i][j]) - 48 == cur:
					sum += 1
				cur += 1
				cur %= 2
		counts.append(sum)
	max = n * n
	counts.sort()
	sum = 0
	for i in range(4):
		if i < 2:
			sum += counts[i]
		else:
			sum += max - counts[i]
	return sum
(n, pieces) = read_data()
print(solve())


n = int(input())
chess = []
for w in range(3):
	chess.append([input() for i in range(n)])
	input()
chess.append([input() for i in range(n)])
issue = {0: 0, 1: 0, 2: 0, 3: 0}
reversed_issue = {0: 0, 1: 0, 3: 0}
for w in range(4):
	chessdesk = [chess[0] + chess[3]] + [chess[1] + chess[2]]
	for s in range(2 * n):
		chessdesk[0][s] += chessdesk[1][s]
	chessdesk.pop(1)
	chessdesk = chessdesk[0]
	colour = chessdesk[0][0]
	for i in range(2 * n):
		for j in range(2 * n):
			if (i + j) % 2 == 0:
				if chessdesk[i][j] != colour:
					issue[w] += 1
			elif chessdesk[i][j] == colour:
				issue[w] += 1
	reversed_issue[w] = 4 * n ** 2 - issue[w]
	if w == 0:
		(chess[0], chess[3]) = (chess[3], chess[0])
	elif w == 1:
		(chess[1], chess[3]) = (chess[3], chess[1])
	elif w == 2:
		(chess[1], chess[2]) = (chess[2], chess[1])
print(min(min(issue.values()), min(reversed_issue.values())))


import itertools
n = int(input())
l = [None] * 4
for _ in range(4):
	tmp = 0
	for i in range(n):
		line = input().strip()
		for (j, s) in enumerate(line):
			tmp += (i + j) % 2 and s == '1' or (not (i + j) % 2 and s == '0')
	l[_] = tmp
	if _ != 3:
		input()
min_ = 1000000
for (i1, i2, i3, i4) in itertools.permutations([0, 1, 2, 3], 4):
	min_ = min(min_, l[i1] + l[i2] + n * n - l[i3] + n * n - l[i4])
print(min_)


from itertools import permutations
n = int(input())
p1 = [input() for _ in range(n)]
input()
p2 = [input() for _ in range(n)]
input()
p3 = [input() for _ in range(n)]
input()
p4 = [input() for _ in range(n)]

def usta(a, b, c, d):
	sza = []
	for i in range(n * 2):
		li = [a, b, c, d]
		if i < n:
			g = min(li)
			if g == a:
				sza.append(p1[i])
			elif g == b:
				sza.append(p2[i])
			elif g == c:
				sza.append(p3[i])
			elif g == d:
				sza.append(p4[i])
			li.remove(g)
			g = min(li)
			if g == a:
				sza[-1] += p1[i]
			elif g == b:
				sza[-1] += p2[i]
			elif g == c:
				sza[-1] += p3[i]
			elif g == d:
				sza[-1] += p4[i]
			li.remove(g)
		else:
			li.remove(min(li))
			li.remove(min(li))
			i -= n
			g = min(li)
			if g == a:
				sza.append(p1[i])
			elif g == b:
				sza.append(p2[i])
			elif g == c:
				sza.append(p3[i])
			elif g == d:
				sza.append(p4[i])
			li.remove(g)
			g = min(li)
			if g == a:
				sza[-1] += p1[i]
			elif g == b:
				sza[-1] += p2[i]
			elif g == c:
				sza[-1] += p3[i]
			elif g == d:
				sza[-1] += p4[i]
			li.remove(g)
	last = True
	c1 = 0
	c2 = 0
	for j in sza:
		b = False if last == True else True
		last = False if last == True else True
		for p in j:
			if b is True:
				if p != '1':
					c1 += 1
				else:
					c2 += 1
			elif p == '1':
				c1 += 1
			else:
				c2 += 1
			b = True if b is False else False
	return min(c1, c2)
out = float('inf')
for per in list(permutations('1234')):
	out = min(out, usta(int(per[0]), int(per[1]), int(per[2]), int(per[3])))
print(out)


from itertools import permutations
n = int(input())
a = []
for i in range(4):
	a.append([list(map(int, list(input()))) for j in range(n)])
	if i < 3:
		input()
ans = 10 ** 10
for i in permutations(a, 4):
	cnt = 0
	total = 0
	for j in i:
		if cnt < 2:
			cnt2 = 0
			for p in j:
				for q in p:
					if q != cnt2 % 2:
						total += 1
					cnt2 += 1
		else:
			cnt2 = 1
			for p in j:
				for q in p:
					if q != cnt2 % 2:
						total += 1
					cnt2 += 1
		cnt += 1
	ans = min(ans, total)
print(ans)


def bubble_sort(a_list):
	changed = True
	while changed:
		changed = False
		for i in range(len(a_list) - 1):
			if a_list[i] > a_list[i + 1]:
				changed = True
				(a_list[i], a_list[i + 1]) = (a_list[i + 1], a_list[i])
	return a_list
n = int(input())
str1 = ''
for i in range(n):
	str1 = str1 + input()
j = input()
str2 = ''
for i in range(n):
	str2 = str2 + input()
j = input()
str3 = ''
for i in range(n):
	str3 = str3 + input()
str4 = ''
j = input()
for i in range(n):
	str4 = str4 + input()
str1comp = '01' * n ** 2
a = 0
b = 0
c = 0
d = 0
for i in range(n ** 2):
	if str1[i] == str1comp[i]:
		a += 1
for i in range(n ** 2):
	if str2[i] == str1comp[i]:
		b += 1
for i in range(n ** 2):
	if str3[i] == str1comp[i]:
		c += 1
for i in range(n ** 2):
	if str4[i] == str1comp[i]:
		d += 1
lst2 = []
lst2.append(a)
lst2.append(b)
lst2.append(c)
lst2.append(d)
bubble_sort(lst2)
sum3 = 0
for i in range(2):
	sum3 += lst2[i]
for i in range(2, 4):
	sum3 += n ** 2 - lst2[i]
print(sum3)


from itertools import permutations as p
rd = lambda : map(int, input())

def f(n, t):
	a = 0
	f = 1
	for i in range(n):
		for x in rd():
			if x != f:
				a += 1
			f = 1 - f
	if t < 3:
		rd()
	return a
n = int(input())
m = []
b = [-1, -1, 1, 1]
for i in range(4):
	m.append(f(n, i))
print(2 * n ** 2 + min((sum((x * y for (x, y) in zip(q, m))) for q in set(p(b)))))


n = int(input())
boards = [0] * 4
for b in range(4):
	for y in range(n):
		line = input()
		for x in range(len(line)):
			if (x + y) % 2 == 0:
				if line[x] == '1':
					boards[b] += 1
			elif line[x] == '0':
				boards[b] += 1
	if b < 3:
		input()
n2 = n * n
boards = sorted(boards)
answer = 2 * n2 + boards[0] + boards[1] - boards[2] - boards[3]
print(answer)


from itertools import permutations

def main():
	n = int(input())
	cb0 = [list(map(int, input())) for _ in range(n)]
	_ = input()
	cb1 = [list(map(int, input())) for _ in range(n)]
	_ = input()
	cb2 = [list(map(int, input())) for _ in range(n)]
	_ = input()
	cb3 = [list(map(int, input())) for _ in range(n)]
	print(solve(n, [cb0, cb1, cb2, cb3]))

def solve(n, cbs):
	return min((cost(n, p) for p in permutations(cbs)))

def cost(n, p):
	n2 = 2 * n
	p2 = [p[:2], p[2:]]
	cost1 = sum((1 for i in range(n2) for j in range(n2) if p2[i // n][j // n][i % n][j % n] == (i + j) % 2))
	cost2 = sum((1 for i in range(n2) for j in range(n2) if p2[i // n][j // n][i % n][j % n] == (i + j + 1) % 2))
	return min(cost1, cost2)
main()


n = int(input())
k1 = []
k2 = []
k3 = []
k4 = []
for i in range(n):
	k1.append(input())
s = input()
for i in range(n):
	k2.append(input())
s = input()
for i in range(n):
	k3.append(input())
s = input()
for i in range(n):
	k4.append(input())
A = []
B = []
for i in range(n):
	if i % 2 == 0:
		A.append('0' + '10' * ((n - 1) // 2))
	else:
		A.append('1' + '01' * ((n - 1) // 2))
for i in range(n):
	if i % 2 == 1:
		B.append('0' + '10' * ((n - 1) // 2))
	else:
		B.append('1' + '01' * ((n - 1) // 2))
D1 = [0] * 2
D2 = [0] * 2
D3 = [0] * 2
D4 = [0] * 2
for i in range(n):
	s = A[i]
	s1 = B[i]
	sk = k1[i]
	for i in range(n):
		if s1[i] != sk[i]:
			D1[0] += 1
		if s[i] != sk[i]:
			D1[1] += 1
for i in range(n):
	s = A[i]
	s1 = B[i]
	sk = k2[i]
	for i in range(n):
		if s1[i] != sk[i]:
			D2[0] += 1
		if s[i] != sk[i]:
			D2[1] += 1
for i in range(n):
	s = A[i]
	s1 = B[i]
	sk = k3[i]
	for i in range(n):
		if s1[i] != sk[i]:
			D3[0] += 1
		if s[i] != sk[i]:
			D3[1] += 1
for i in range(n):
	s = A[i]
	s1 = B[i]
	sk = k4[i]
	for i in range(n):
		if s1[i] != sk[i]:
			D4[0] += 1
		if s[i] != sk[i]:
			D4[1] += 1
min_o = 10000000000000000
if min_o > D1[0] + D2[0] + D3[1] + D4[1]:
	min_o = D1[0] + D2[0] + D3[1] + D4[1]
if min_o > D1[0] + D2[1] + D3[0] + D4[1]:
	min_o = D1[0] + D2[1] + D3[0] + D4[1]
if min_o > D1[0] + D2[1] + D3[1] + D4[0]:
	min_o = D1[0] + D2[1] + D3[1] + D4[0]
if min_o > D1[1] + D2[0] + D3[0] + D4[1]:
	min_o = D1[1] + D2[0] + D3[0] + D4[1]
if min_o > D1[1] + D2[0] + D3[1] + D4[0]:
	min_o = D1[1] + D2[0] + D3[1] + D4[0]
if min_o > D1[1] + D2[1] + D3[0] + D4[0]:
	min_o = D1[1] + D2[1] + D3[0] + D4[0]
print(min_o)


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()
n = inp()
s = []
for _ in range(4):
	tmp = [input() for i in range(n)]
	if _ < 3:
		input()
	s.append(tmp)
res = INF
for pt in itertools.combinations(range(4), 2):
	cnt = 0
	for k in range(4):
		f = 1 if k in pt else 0
		for i in range(n):
			for j in range(n):
				if (i + j + f) % 2 != int(s[k][i][j]):
					cnt += 1
	res = min(res, cnt)
print(res)


n = int(input())
brd = []
for i in range(4):
	brd.append([list(map(int, list(input()))) for _ in range(n)])
	if i < 3:
		_ = input()
ans = 4 * n ** 2
for i in range(16):
	if sum([i >> j & 1 for j in range(4)]) != 2:
		continue
	ans = min(ans, sum([abs((r + c + (i >> j & 1)) % 2 - brd[j][r][c]) for j in range(4) for r in range(n) for c in range(n)]))
print(ans)


n = int(input())

def func(a, li):
	global n
	ans = 0
	for i in range(n):
		for j in range(n):
			if a[i][j] != li[i][j]:
				ans = ans + 1
	return ans
a = []
for i in range(n // 2):
	a.append('10' * (n // 2) + '1')
	a.append('01' * (n // 2) + '0')
a.append('10' * (n // 2) + '1')
nums = []
for j in range(4):
	li = []
	for k in range(n):
		li.append(input())
	nums.append(func(a, li))
	if j != 3:
		input()
nums = sorted(nums)
x = n * n
print(nums[0] + nums[1] + (x - nums[2]) + (x - nums[3]))


n = int(input())
b1 = [input() for i in range(n)]
input()
b2 = [input() for i in range(n)]
input()
b3 = [input() for i in range(n)]
input()
b4 = [input() for i in range(n)]
minflip = n * n * 4
bb = []
bb.append(b1 + b2 + b3 + b4)
bb.append(b1 + b3 + b2 + b4)
bb.append(b1 + b2 + b4 + b3)
for b in bb:
	currflip = 0
	for i in range(len(b)):
		for j in range(len(b[0])):
			if int(b[i][j]) != (i + j) % 2:
				currflip += 1
	if currflip < minflip:
		minflip = currflip
	currflip = 0
	for i in range(len(b)):
		for j in range(len(b[0])):
			if int(b[i][j]) == (i + j) % 2:
				currflip += 1
	if currflip < minflip:
		minflip = currflip
print(minflip)


import sys
input = sys.stdin.readline

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
n = int(input())
board = []
for _ in range(4):
	mine = []
	for i in range(n):
		mine.append(list(input().strip()))
	board.append(mine)
	if _ != 3:
		literally_useless = input().strip()
one = [['0' for _ in range(n)] for __ in range(n)]
zero = [['1' for _ in range(n)] for __ in range(n)]
for i in range(n):
	for j in range(n):
		if i + j & 1:
			one[i][j] = '1'
			zero[i][j] = '0'
one_d = []
zero_d = []
for i in range(4):
	count_one = 0
	count_zero = 0
	for j in range(n):
		for k in range(n):
			if board[i][j][k] != one[j][k]:
				count_one += 1
			if board[i][j][k] != zero[j][k]:
				count_zero += 1
	one_d.append(count_one)
	zero_d.append(count_zero)
ans = INF
for i in range(4):
	for j in range(4):
		if i == j:
			continue
		this = [0, 1, 2, 3]
		this.remove(i)
		this.remove(j)
		kaguya = one_d[i] + one_d[j] + zero_d[this[0]] + zero_d[this[1]]
		ans = min(ans, kaguya)
print(ans)


def morph(desk, cur):
	k = 0
	for i in range(len(desk)):
		for j in range(len(desk)):
			if desk[i][j] != cur:
				k += 1
			cur = 1 - cur
	return k
n = int(input())
mf = []
m1 = []
m2 = []
m3 = []
m4 = []
for i in range(n):
	m = []
	s = input()
	for j in s:
		m.append(int(j))
	m1.append(m)
s = input()
for i in range(n):
	m = []
	s = input()
	for j in s:
		m.append(int(j))
	m2.append(m)
s = input()
for i in range(n):
	m = []
	s = input()
	for j in s:
		m.append(int(j))
	m3.append(m)
s = input()
for i in range(n):
	m = []
	s = input()
	for j in s:
		m.append(int(j))
	m4.append(m)
mf.append(m1)
mf.append(m2)
mf.append(m3)
mf.append(m4)
min = 4 * n * n + 1
for i in range(4):
	for j in range(i + 1, 4):
		cur = 0
		cur += morph(mf[i], 1)
		cur += morph(mf[j], 1)
		for k in range(4):
			if k != i and k != j:
				cur += morph(mf[k], 0)
		if cur < min:
			min = cur
print(min)


n = int(input())
Map = [[], [], [], []]
for x in range(4):
	for i in range(n):
		inp = list(input())
		Map[x].append(inp)
	if x != 3:
		input()
mini = 1000000000000000
ideal = [[], [], [], []]
for i in range(n):
	ideal[1].append([])
	ideal[0].append([])
	for j in range(n):
		if (i % 2 == 0) ^ (j % 2 == 0):
			ideal[0][i].append('1')
			ideal[1][i].append('0')
		else:
			ideal[1][i].append('1')
			ideal[0][i].append('0')
ideal[2] = ideal[0]
ideal[3] = ideal[1]
for one in range(4):
	for two in range(4):
		for three in range(4):
			for four in range(4):
				if one != two and one != three and (one != four) and (two != three) and (two != four) and (three != four):
					count = 0
					for i in range(n):
						for j in range(n):
							if Map[one][i][j] != ideal[0][i][j]:
								count += 1
							if Map[two][i][j] != ideal[1][i][j]:
								count += 1
							if Map[three][i][j] != ideal[2][i][j]:
								count += 1
							if Map[four][i][j] != ideal[3][i][j]:
								count += 1
					mini = min(mini, count)
print(mini)


import itertools
n = int(input())
t1 = [[] for i in range(n)]
t2 = [[] for i in range(n)]
t3 = [[] for i in range(n)]
t4 = [[] for i in range(n)]
for i in range(n):
	a = list(input())
	t1[i] = a
w = input()
for i in range(n):
	a = list(input())
	t2[i] = a
w = input()
for i in range(n):
	a = list(input())
	t3[i] = a
w = input()
for i in range(n):
	a = list(input())
	t4[i] = a
(rec1, rec2) = ([0, 0, 0, 0], [0, 0, 0, 0])
for i in range(n):
	if i % 2 == 0:
		p = 1
	else:
		p = 0
	for j in range(n):
		if int(t1[i][j]) != p:
			rec1[0] += 1
		else:
			rec2[0] += 1
		p ^= 1
for i in range(n):
	if i % 2 == 0:
		p = 1
	else:
		p = 0
	for j in range(n):
		if int(t2[i][j]) != p:
			rec1[1] += 1
		else:
			rec2[1] += 1
		p ^= 1
for i in range(n):
	if i % 2 == 0:
		p = 1
	else:
		p = 0
	for j in range(n):
		if int(t3[i][j]) != p:
			rec1[2] += 1
		else:
			rec2[2] += 1
		p ^= 1
for i in range(n):
	if i % 2 == 0:
		p = 1
	else:
		p = 0
	for j in range(n):
		if int(t4[i][j]) != p:
			rec1[3] += 1
		else:
			rec2[3] += 1
		p ^= 1
R = [0, 1, 2, 3]
num = float('inf')
for (a, b, c, d) in itertools.permutations(R, 4):
	num = min(num, rec1[a] + rec1[b] + rec2[c] + rec2[d])
print(num)


from bisect import bisect_left as bl, bisect_right as br, insort
import sys
import heapq
from math import *
from collections import defaultdict as dd, deque

def data():
	return sys.stdin.readline().strip()

def mdata():
	return map(int, data().split())
n = int(data())
s = [[0, 0] for i in range(4)]
for i in range(4):
	t = 1
	temp = 0
	for j in range(n):
		l = input()
		if j == 0 and l[0] == '0':
			t = 0
		for k in range(n):
			if (j + k) % 2 == 0 and int(l[k]) != t or ((j + k) % 2 == 1 and int(l[k]) != 1 - t):
				temp += 1
	if i != 3:
		input()
	s[i][t] = temp
	s[i][1 - t] = n * n - temp
ans = 100000000000
for i in range(4):
	for j in range(i + 1, 4):
		t = s[i][0] + s[j][0]
		for k in range(4):
			if k != j and k != i:
				t += s[k][1]
		ans = min(ans, t)
print(ans)


from functools import reduce
import math
from decimal import *

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def sol():
	am = int(input())
	pieces = []
	need1 = [0] * 4
	need2 = [0] * 4
	for i in range(4):
		piece = []
		for g in range(am):
			piece.append(list(map(int, list(input()))))
		for g in range(am):
			for j in range(am):
				need1[i] += (piece[g][j] == (j & 1 == g & 1)) + 1 & 1
		if i != 3:
			input()
		pieces.append(piece)
	need1.sort()
	s = 0
	for i in range(2):
		s += need1[i]
	for i in range(2, 4):
		s += am ** 2 - need1[i]
	print(s)
sol()


rd = lambda : map(int, input())

def f(n, t):
	a = sum((i + j & 1 == x for i in range(n) for (j, x) in enumerate(rd())))
	if t < 3:
		rd()
	return a
n = int(input())
m = sorted([f(n, i) for i in range(4)])
print(2 * n * n + m[0] + m[1] - m[2] - m[3])


import sys
from itertools import permutations
n = int(input())
board = []
for i in range(4):
	board.append([list(map(int, input())) for _ in range(n)])
	if i < 3:
		input()

def solve(a, b, c, d):
	mat = []
	for i in range(n):
		mat.append(board[a][i] + board[b][i])
	for i in range(n):
		mat.append(board[c][i] + board[d][i])
	(res, color) = (0, 0)
	for i in range(2 * n):
		for j in range(2 * n):
			if mat[i][j] == color:
				res += 1
			color ^= 1
		color ^= 1
	return min(res, (2 * n) ** 2 - res)
ans = 10 ** 9
for a in permutations(range(4)):
	ans = min(ans, solve(*a))
print(ans)


def divisors(M):
	d = []
	i = 1
	while M >= i ** 2:
		if M % i == 0:
			d.append(i)
			if i ** 2 != M:
				d.append(M // i)
		i = i + 1
	return d

def popcount(x):
	x = x - (x >> 1 & 1431655765)
	x = (x & 858993459) + (x >> 2 & 858993459)
	x = x + (x >> 4) & 252645135
	x = x + (x >> 8)
	x = x + (x >> 16)
	return x & 127

def eratosthenes(n):
	res = [0 for i in range(n + 1)]
	prime = set([])
	for i in range(2, n + 1):
		if not res[i]:
			prime.add(i)
			for j in range(1, n // i + 1):
				res[i * j] = 1
	return prime

def factorization(n):
	res = []
	for p in prime:
		if n % p == 0:
			while n % p == 0:
				n //= p
			res.append(p)
	if n != 1:
		res.append(n)
	return res

def euler_phi(n):
	res = n
	for x in range(2, n + 1):
		if x ** 2 > n:
			break
		if n % x == 0:
			res = res // x * (x - 1)
			while n % x == 0:
				n //= x
	if n != 1:
		res = res // n * (n - 1)
	return res

def ind(b, n):
	res = 0
	while n % b == 0:
		res += 1
		n //= b
	return res

def isPrimeMR(n):
	d = n - 1
	d = d // (d & -d)
	L = [2, 3, 5, 7, 11, 13, 17]
	for a in L:
		t = d
		y = pow(a, t, n)
		if y == 1:
			continue
		while y != n - 1:
			y = y * y % n
			if y == 1 or t == n - 1:
				return 0
			t <<= 1
	return 1

def findFactorRho(n):
	from math import gcd
	m = 1 << n.bit_length() // 8
	for c in range(1, 99):
		f = lambda x: (x * x + c) % n
		(y, r, q, g) = (2, 1, 1, 1)
		while g == 1:
			x = y
			for i in range(r):
				y = f(y)
			k = 0
			while k < r and g == 1:
				ys = y
				for i in range(min(m, r - k)):
					y = f(y)
					q = q * abs(x - y) % n
				g = gcd(q, n)
				k += m
			r <<= 1
		if g == n:
			g = 1
			while g == 1:
				ys = f(ys)
				g = gcd(abs(x - ys), n)
		if g < n:
			if isPrimeMR(g):
				return g
			elif isPrimeMR(n // g):
				return n // g
			return findFactorRho(g)

def primeFactor(n):
	i = 2
	ret = {}
	rhoFlg = 0
	while i * i <= n:
		k = 0
		while n % i == 0:
			n //= i
			k += 1
		if k:
			ret[i] = k
		i += 1 + i % 2
		if i == 101 and n >= 2 ** 20:
			while n > 1:
				if isPrimeMR(n):
					(ret[n], n) = (1, 1)
				else:
					rhoFlg = 1
					j = findFactorRho(n)
					k = 0
					while n % j == 0:
						n //= j
						k += 1
					ret[j] = k
	if n > 1:
		ret[n] = 1
	if rhoFlg:
		ret = {x: ret[x] for x in sorted(ret)}
	return ret

def divisors(n):
	res = [1]
	prime = primeFactor(n)
	for p in prime:
		newres = []
		for d in res:
			for j in range(prime[p] + 1):
				newres.append(d * p ** j)
		res = newres
	res.sort()
	return res

def xorfactorial(num):
	if num == 0:
		return 0
	elif num == 1:
		return 1
	elif num == 2:
		return 3
	elif num == 3:
		return 0
	else:
		x = baseorder(num)
		return 2 ** x * ((num - 2 ** x + 1) % 2) + function(num - 2 ** x)

def xorconv(n, X, Y):
	if n == 0:
		res = [X[0] * Y[0] % mod]
		return res
	x = [X[i] + X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	y = [Y[i] + Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	z = [X[i] - X[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	w = [Y[i] - Y[i + 2 ** (n - 1)] for i in range(2 ** (n - 1))]
	res1 = xorconv(n - 1, x, y)
	res2 = xorconv(n - 1, z, w)
	former = [(res1[i] + res2[i]) * inv for i in range(2 ** (n - 1))]
	latter = [(res1[i] - res2[i]) * inv for i in range(2 ** (n - 1))]
	former = list(map(lambda x: x % mod, former))
	latter = list(map(lambda x: x % mod, latter))
	return former + latter

def merge_sort(A, B):
	(pos_A, pos_B) = (0, 0)
	(n, m) = (len(A), len(B))
	res = []
	while pos_A < n and pos_B < m:
		(a, b) = (A[pos_A], B[pos_B])
		if a < b:
			res.append(a)
			pos_A += 1
		else:
			res.append(b)
			pos_B += 1
	res += A[pos_A:]
	res += B[pos_B:]
	return res

class UnionFindVerSize:

	def __init__(self, N):
		self._parent = [n for n in range(0, N)]
		self._size = [1] * N
		self.group = N

	def find_root(self, x):
		if self._parent[x] == x:
			return x
		self._parent[x] = self.find_root(self._parent[x])
		stack = [x]
		while self._parent[stack[-1]] != stack[-1]:
			stack.append(self._parent[stack[-1]])
		for v in stack:
			self._parent[v] = stack[-1]
		return self._parent[x]

	def unite(self, x, y):
		gx = self.find_root(x)
		gy = self.find_root(y)
		if gx == gy:
			return
		self.group -= 1
		if self._size[gx] < self._size[gy]:
			self._parent[gx] = gy
			self._size[gy] += self._size[gx]
		else:
			self._parent[gy] = gx
			self._size[gx] += self._size[gy]

	def get_size(self, x):
		return self._size[self.find_root(x)]

	def is_same_group(self, x, y):
		return self.find_root(x) == self.find_root(y)

class WeightedUnionFind:

	def __init__(self, N):
		self.parent = [i for i in range(N)]
		self.size = [1 for i in range(N)]
		self.val = [0 for i in range(N)]
		self.flag = True
		self.edge = [[] for i in range(N)]

	def dfs(self, v, pv):
		stack = [(v, pv)]
		new_parent = self.parent[pv]
		while stack:
			(v, pv) = stack.pop()
			self.parent[v] = new_parent
			for (nv, w) in self.edge[v]:
				if nv != pv:
					self.val[nv] = self.val[v] + w
					stack.append((nv, v))

	def unite(self, x, y, w):
		if not self.flag:
			return
		if self.parent[x] == self.parent[y]:
			self.flag = self.val[x] - self.val[y] == w
			return
		if self.size[self.parent[x]] > self.size[self.parent[y]]:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[x] += self.size[y]
			self.val[y] = self.val[x] - w
			self.dfs(y, x)
		else:
			self.edge[x].append((y, -w))
			self.edge[y].append((x, w))
			self.size[y] += self.size[x]
			self.val[x] = self.val[y] + w
			self.dfs(x, y)

class Dijkstra:

	class Edge:

		def __init__(self, _to, _cost):
			self.to = _to
			self.cost = _cost

	def __init__(self, V):
		self.G = [[] for i in range(V)]
		self._E = 0
		self._V = V

	@property
	def E(self):
		return self._E

	@property
	def V(self):
		return self._V

	def add_edge(self, _from, _to, _cost):
		self.G[_from].append(self.Edge(_to, _cost))
		self._E += 1

	def shortest_path(self, s):
		import heapq
		que = []
		d = [10 ** 15] * self.V
		d[s] = 0
		heapq.heappush(que, (0, s))
		while len(que) != 0:
			(cost, v) = heapq.heappop(que)
			if d[v] < cost:
				continue
			for i in range(len(self.G[v])):
				e = self.G[v][i]
				if d[e.to] > d[v] + e.cost:
					d[e.to] = d[v] + e.cost
					heapq.heappush(que, (d[e.to], e.to))
		return d

def Z_algorithm(s):
	N = len(s)
	Z_alg = [0] * N
	Z_alg[0] = N
	i = 1
	j = 0
	while i < N:
		while i + j < N and s[j] == s[i + j]:
			j += 1
		Z_alg[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < N and k + Z_alg[k] < j:
			Z_alg[i + k] = Z_alg[k]
			k += 1
		i += k
		j -= k
	return Z_alg

class BIT:

	def __init__(self, n):
		self.BIT = [0] * (n + 1)
		self.num = n

	def query(self, idx):
		res_sum = 0
		while idx > 0:
			res_sum += self.BIT[idx]
			idx -= idx & -idx
		return res_sum

	def update(self, idx, x):
		while idx <= self.num:
			self.BIT[idx] += x
			idx += idx & -idx
		return

class dancinglink:

	def __init__(self, n, debug=False):
		self.n = n
		self.debug = debug
		self._left = [i - 1 for i in range(n)]
		self._right = [i + 1 for i in range(n)]
		self.exist = [True for i in range(n)]

	def pop(self, k):
		if self.debug:
			assert self.exist[k]
		L = self._left[k]
		R = self._right[k]
		if L != -1:
			if R != self.n:
				(self._right[L], self._left[R]) = (R, L)
			else:
				self._right[L] = self.n
		elif R != self.n:
			self._left[R] = -1
		self.exist[k] = False

	def left(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._left[res]
			if res == -1:
				break
			k -= 1
		return res

	def right(self, idx, k=1):
		if self.debug:
			assert self.exist[idx]
		res = idx
		while k:
			res = self._right[res]
			if res == self.n:
				break
			k -= 1
		return res

class SparseTable:

	def __init__(self, A, merge_func, ide_ele):
		N = len(A)
		n = N.bit_length()
		self.table = [[ide_ele for i in range(n)] for i in range(N)]
		self.merge_func = merge_func
		for i in range(N):
			self.table[i][0] = A[i]
		for j in range(1, n):
			for i in range(0, N - 2 ** j + 1):
				f = self.table[i][j - 1]
				s = self.table[i + 2 ** (j - 1)][j - 1]
				self.table[i][j] = self.merge_func(f, s)

	def query(self, s, t):
		b = t - s + 1
		m = b.bit_length() - 1
		return self.merge_func(self.table[s][m], self.table[t - 2 ** m + 1][m])

class BinaryTrie:

	class node:

		def __init__(self, val):
			self.left = None
			self.right = None
			self.max = val

	def __init__(self):
		self.root = self.node(-10 ** 15)

	def append(self, key, val):
		pos = self.root
		for i in range(29, -1, -1):
			pos.max = max(pos.max, val)
			if key >> i & 1:
				if pos.right is None:
					pos.right = self.node(val)
					pos = pos.right
				else:
					pos = pos.right
			elif pos.left is None:
				pos.left = self.node(val)
				pos = pos.left
			else:
				pos = pos.left
		pos.max = max(pos.max, val)

	def search(self, M, xor):
		res = -10 ** 15
		pos = self.root
		for i in range(29, -1, -1):
			if pos is None:
				break
			if M >> i & 1:
				if xor >> i & 1:
					if pos.right:
						res = max(res, pos.right.max)
					pos = pos.left
				else:
					if pos.left:
						res = max(res, pos.left.max)
					pos = pos.right
			elif xor >> i & 1:
				pos = pos.right
			else:
				pos = pos.left
		if pos:
			res = max(res, pos.max)
		return res

def solveequation(edge, ans, n, m):
	x = [0] * m
	used = [False] * n
	for v in range(n):
		if used[v]:
			continue
		y = dfs(v)
		if y != 0:
			return False
	return x

	def dfs(v):
		used[v] = True
		r = ans[v]
		for (to, dire, id) in edge[v]:
			if used[to]:
				continue
			y = dfs(to)
			if dire == -1:
				x[id] = y
			else:
				x[id] = -y
			r += y
		return r

class Matrix:
	mod = 10 ** 9 + 7

	def set_mod(m):
		Matrix.mod = m

	def __init__(self, L):
		self.row = len(L)
		self.column = len(L[0])
		self._matrix = L
		for i in range(self.row):
			for j in range(self.column):
				self._matrix[i][j] %= Matrix.mod

	def __getitem__(self, item):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		return self._matrix[i][j]

	def __setitem__(self, item, val):
		if type(item) == int:
			raise IndexError('you must specific row and column')
		elif len(item) != 2:
			raise IndexError('you must specific row and column')
		(i, j) = item
		self._matrix[i][j] = val

	def __add__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matrix[i][j] + other._matrix[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __sub__(self, other):
		if (self.row, self.column) != (other.row, other.column):
			raise SizeError('sizes of matrixes are different')
		res = [[0 for j in range(self.column)] for i in range(self.row)]
		for i in range(self.row):
			for j in range(self.column):
				res[i][j] = self._matrix[i][j] - other._matrix[i][j]
				res[i][j] %= Matrix.mod
		return Matrix(res)

	def __mul__(self, other):
		if type(other) != int:
			if self.column != other.row:
				raise SizeError('sizes of matrixes are different')
			res = [[0 for j in range(other.column)] for i in range(self.row)]
			for i in range(self.row):
				for j in range(other.column):
					temp = 0
					for k in range(self.column):
						temp += self._matrix[i][k] * other._matrix[k][j]
					res[i][j] = temp % Matrix.mod
			return Matrix(res)
		else:
			n = other
			res = [[n * self._matrix[i][j] % Matrix.mod for j in range(self.column)] for i in range(self.row)]
			return Matrix(res)

	def __pow__(self, m):
		if self.column != self.row:
			raise MatrixPowError('the size of row must be the same as that of column')
		n = self.row
		res = Matrix([[int(i == j) for i in range(n)] for j in range(n)])
		while m:
			if m % 2 == 1:
				res = res * self
			self = self * self
			m //= 2
		return res

	def __str__(self):
		res = []
		for i in range(self.row):
			for j in range(self.column):
				res.append(str(self._matrix[i][j]))
				res.append(' ')
			res.append('\n')
		res = res[:len(res) - 1]
		return ''.join(res)
import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
from itertools import permutations
from math import log, gcd
input = lambda : sys.stdin.readline().rstrip()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
n = int(input())
P = permutations([i for i in range(4)])
plus = [(0, 0), (0, n), (n, 0), (n, n)]
A = []
for i in range(4):
	tmp = [input() for i in range(n)]
	if i != 3:
		_ = input()
	A.append(tmp)
tmp = [[0 for i in range(2 * n)] for j in range(2 * n)]
res = 10 ** 17
for p in P:
	for k in range(4):
		(x, y) = plus[p[k]]
		for i in range(n):
			for j in range(n):
				tmp[i + x][j + y] = int(A[k][i][j])
	ans_1 = 0
	ans_2 = 0
	for i in range(2 * n):
		for j in range(2 * n):
			if tmp[i][j] == (i + j) % 2:
				ans_1 += 1
			else:
				ans_2 += 1
	res = min(res, ans_1, ans_2)
print(res)


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def main():
	n = int(input())
	s = []
	for i in range(4):
		df = 0
		for k in range(n):
			l = input()
			for j in range(n):
				if int(l[j]) == (k + j) % 2:
					df += 1
		if i < 3:
			input()
		s.append(df)
	print(min(s[0] + s[1] + n * n - s[2] + n * n - s[3], s[0] + s[2] + n * n - s[1] + n * n - s[3], s[0] + s[3] + n * n - s[1] + n * n - s[2], s[1] + s[2] + n * n - s[0] + n * n - s[3], s[1] + s[3] + n * n - s[0] + n * n - s[2], s[2] + s[3] + n * n - s[0] + n * n - s[1]))
main()


n = int(input())
s = [['' for _ in range(n)] for __ in range(4)]
for i in range(3):
	for j in range(n):
		s[i][j] = input()
	input()
for j in range(n):
	s[3][j] = input()
res = int(10000000000000.0)
for i in range(24):
	perm = [0, 1, 2, 3]
	L = [0] * 4
	tmp = i
	for j in range(4):
		L[j] = tmp % (4 - j)
		tmp //= 4 - j
	LL = [0] * 4
	for j in range(4):
		LL[j] = perm[L[j]]
		for k in range(L[j], 3 - j):
			perm[k] = perm[k + 1]
	(lu, ru, ld, rd) = (LL[0], LL[1], LL[2], LL[3])
	Map = [s[lu][_][:] + s[ru][_][:] for _ in range(n)] + [s[ld][_][:] + s[rd][_][:] for _ in range(n)]
	(cnt0, cnt1) = (0, 0)
	for j in range(2 * n):
		for k in range(2 * n):
			if (j + k) % 2:
				if Map[j][k] == '0':
					cnt0 += 1
				else:
					cnt1 += 1
			elif Map[j][k] == '1':
				cnt0 += 1
			else:
				cnt1 += 1
	res = min(res, cnt0, cnt1)
print(res)


n = int(input())
block = []

def flip(ch):
	return '1' if ch == '0' else '0'
for i in range(4):
	if i:
		input()
	left = '1'
	c0 = c1 = 0
	for j in range(n):
		s = input()
		expect = left
		for c in s:
			if c == expect:
				c0 += 1
			else:
				c1 += 1
			expect = flip(expect)
		left = flip(left)
	block.append([c0, c1])
ans = 4 * n * n
import itertools
for (a, b, c, d) in itertools.permutations(range(4), 4):
	v = block[a][0] + block[b][0] + block[c][1] + block[d][1]
	ans = min(ans, v)
print(ans)


n = int(input())

def Count(s, flags):
	a = str(flags)
	b = str(1 - flags)
	c = 0
	for i in range(len(s)):
		if i % 2 and s[i] != b or (not i % 2 and s[i] != a):
			c += 1
	return c

def ReadPieces():
	s0 = s1 = 0
	for i in range(n):
		s = input()
		if not s:
			s = input()
		s0 += Count(s, i % 2)
		s1 += Count(s, (i + 1) % 2)
	return (s0, s1)
b = []
for i in range(4):
	(a0, a1) = ReadPieces()
	b.append([a0, a1])

def f(i, j):
	s = 0
	for k in range(4):
		if k == i or k == j:
			s += b[k][0]
		else:
			s += b[k][1]
	return s
print(min(f(0, 1), f(0, 2), f(0, 3), f(1, 2), f(1, 3), f(2, 3)))


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
import itertools

def main():
	n = int(input())
	segments = []
	for _ in range(3):
		segments.append([input() for x in range(n)])
		input()
	segments.append([input() for x in range(n)])
	diffs = []
	for seg in segments:
		diff = 0
		for i in range(n):
			for j in range(n):
				if int(seg[i][j]) == (i + j) % 2:
					diff += 1
		diffs.append(diff)
	diff_sum = sum(diffs)
	print(min((diff_sum - a - b + (n * n - a) + (n * n - b) for (a, b) in itertools.combinations(diffs, 2))))
main()


from itertools import permutations

def count(board, first_square):
	cnt = 0
	n = len(board)
	same = str(first_square)
	inverted = str(1 - first_square)
	for i in range(n):
		for j in range(n):
			if (i + j) % 2 == 0:
				c = same
			else:
				c = inverted
			cnt += board[i][j] != c
	return cnt

def main():
	n = int(input())
	m = n * n * 4
	pieces = []
	for _ in range(4):
		piece = []
		for i in range(n):
			piece.append(input())
		pieces.append(piece)
		try:
			input()
		except:
			pass
	for color in range(2):
		for p in permutations(range(4)):
			changed = count(pieces[p[0]], color) + count(pieces[p[1]], 1 - color) + count(pieces[p[2]], 1 - color) + count(pieces[p[3]], color)
			if changed < m:
				m = changed
	print(m)
main()


def diff_start_zero(board):
	chars = ['0', '1']
	i = 0
	difference = 0
	for i in range(n * n):
		if board[i] != chars[i % 2]:
			difference += 1
	return difference
n = int(input())
boards = []
for i in range(4):
	board = ''
	for j in range(n):
		board += input()
	boards.append(board)
	board = ''
	if i < 3:
		input()
zero_diffs = [diff_start_zero(i) for i in boards]
one_diffs = [n * n - i for i in zero_diffs]
pairs = [(a, b) for (a, b) in zip(zero_diffs, one_diffs)]
pairs.sort()
result = pairs[0][0] + pairs[1][0] + pairs[2][1] + pairs[3][1]
print(result)


import math
n = int(input())
parts = []
for i in range(0, 4):
	part = []
	for j in range(0, n):
		part.append(int(input(), 2))
	if i < 3:
		input()
	parts.append(part)
mask = 0
for i in range(0, int((n + 1) / 2)):
	mask += int(math.pow(2, 2 * i))

def onesCount(num):
	counter = 0
	while num != 0:
		if num & 1 == 1:
			counter += 1
		num = num >> 1
	return counter
difs = []
for part in parts:
	dif = 0
	for i in range(0, n):
		if i % 2 == 0:
			dif += onesCount(part[i] ^ mask)
		else:
			dif += n - onesCount(part[i] ^ mask)
	difs.append(dif)
difs.sort()
min = difs[0] + difs[1] + (n * n - difs[2]) + (n * n - difs[3])
print(min)


from sys import stdin
input = stdin.readline
n = int(input())
a = []
for i in range(4):
	a.append([[int(x) for x in list(input().rstrip())] for _ in range(n)])
	if i < 3:
		input()
b = []
for i in range(4):
	b.append([])
	for j in range(2):
		c = 0
		for y in range(n):
			for x in range(n):
				if j == 1:
					z = (x + y) % 2
				else:
					z = 1 - (x + y) % 2
				c += a[i][y][x] != z
		b[-1].append(c)
ans = float('inf')
for i in (3, 5, 6, 9, 10, 12):
	ans = min(ans, b[0][i & 1] + b[1][i >> 1 & 1] + b[2][i >> 2 & 1] + b[3][i >> 3 & 1])
print(ans)


n = int(input())
temp = [0 for _ in range(4)]
for k in range(4):
	for i in range(n):
		str = input()
		for j in range(n):
			if (i + j) % 2 == int(str[j]):
				temp[k] += 1
	if k < 3:
		input()
temp.sort()
print(temp[0] + temp[1] + 2 * n * n - temp[2] - temp[3])


from itertools import permutations
pieces = []
n = int(input())
for i in range(4):
	part = []
	for j in range(n):
		part.append(input())
	if i != 3:
		input()
	pieces.append(part)
mindiffs = 10 ** 9
preMade = [['0' if x % 2 == 0 else '1' for x in range(2 * n)], ['0' if x % 2 == 1 else '1' for x in range(2 * n)]]
for a in permutations('0123', 4):
	indexes = list(map(int, a))
	currentBoard = []
	for i in range(n):
		currentBoard.append(pieces[indexes[0]][i] + pieces[indexes[1]][i])
	for i in range(n):
		currentBoard.append(pieces[indexes[2]][i] + pieces[indexes[3]][i])
	for i in range(2):
		startval = i
		currentDiffs = 0
		for j in range(2 * n):
			currentDiffs += bin(int(''.join(preMade[startval]), 2) ^ int(''.join(currentBoard[j]), 2)).count('1')
			startval = (startval + 1) % 2
		mindiffs = min(mindiffs, currentDiffs)
print(mindiffs)


import collections, math
local = False
if local:
	file = open('inputt.txt', 'r')

def inp():
	if local:
		return file.readline().rstrip()
	else:
		return input().rstrip()

def ints():
	return [int(_) for _ in inp().split()]
n = int(inp())
k = [[] for _ in range(4)]
for i in range(4):
	grid = ['' for _ in range(n)]
	for _ in range(n):
		grid[_] = inp()
	if i < 3:
		inp()
	k[i] = grid
goBlackCrossCount = [0] * 4
for i in range(4):
	grid = k[i]
	for r in range(n):
		for c in range(n):
			if r % 2 == 0:
				if c % 2 == 0:
					if grid[r][c] == '1':
						goBlackCrossCount[i] += 1
				elif grid[r][c] == '0':
					goBlackCrossCount[i] += 1
			elif c % 2 == 0:
				if grid[r][c] == '0':
					goBlackCrossCount[i] += 1
			elif grid[r][c] == '1':
				goBlackCrossCount[i] += 1
goBlackCrossCount.sort()
ans = goBlackCrossCount[0] + goBlackCrossCount[1] + n ** 2 - goBlackCrossCount[2] + n ** 2 - goBlackCrossCount[3]
print(ans)


def score(grid, tl):
	n = len(grid)
	ans = 0
	for i in range(n):
		for j in range(n):
			ans += int(grid[i][j]) ^ i & 1 ^ j & 1 ^ tl
	return ans

def main():
	n = int(input())
	first = True
	grids = []
	for _ in range(4):
		if not first:
			input()
		first = False
		grids.append([input() for _ in range(n)])
	a = [score(grid, 0) for grid in grids]
	b = [score(grid, 1) for grid in grids]
	ans = float('inf')
	for i in range(4):
		for j in range(i + 1, 4):
			ans = min(ans, sum(a) - a[i] - a[j] + b[i] + b[j])
	print(ans)
main()


n = int(input())
L = []
for k in range(4):
	x = 0
	for i in range(n):
		A = list(map(int, input()))
		for j in range(n):
			x += A[j] ^ (i - j) % 2
	L.append([x, n ** 2 - x])
	if k != 3:
		input()
out = 4 * n ** 2
for i in range(4):
	for j in range(i + 1, 4):
		(p, q) = list({0, 1, 2, 3} - {i, j})
		out = min(out, L[i][0] + L[j][0] + L[p][1] + L[q][1])
print(out)


n = int(input())
A = []
for _ in range(n):
	A.append(input())
blank = input()
B = []
for _ in range(n):
	B.append(input())
blank = input()
C = []
for _ in range(n):
	C.append(input())
blank = input()
D = []
for _ in range(n):
	D.append(input())
ret = 999999
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '0':
				cnt += 1
		elif A[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '0':
				cnt += 1
		elif B[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '1':
				cnt += 1
		elif C[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '1':
				cnt += 1
		elif D[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '0':
				cnt += 1
		elif A[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '0':
				cnt += 1
		elif C[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '1':
				cnt += 1
		elif B[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '1':
				cnt += 1
		elif D[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '0':
				cnt += 1
		elif A[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '0':
				cnt += 1
		elif D[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '1':
				cnt += 1
		elif C[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '1':
				cnt += 1
		elif B[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '0':
				cnt += 1
		elif B[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '0':
				cnt += 1
		elif C[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '1':
				cnt += 1
		elif A[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '1':
				cnt += 1
		elif D[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '0':
				cnt += 1
		elif D[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '0':
				cnt += 1
		elif B[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '1':
				cnt += 1
		elif C[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '1':
				cnt += 1
		elif A[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if C[i][j] == '0':
				cnt += 1
		elif C[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if D[i][j] == '0':
				cnt += 1
		elif D[i][j] == '1':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if A[i][j] == '1':
				cnt += 1
		elif A[i][j] == '0':
			cnt += 1
for i in range(n):
	for j in range(n):
		if (i + j) % 2 == 0:
			if B[i][j] == '1':
				cnt += 1
		elif B[i][j] == '0':
			cnt += 1
ret = min(ret, cnt)
cnt = 0
print(ret)


import sys
n = int(sys.stdin.readline().strip())
blks = []
for i in range(4):
	blks.append([])
	for j in range(n):
		blks[-1].append(sys.stdin.readline().strip())
	if i != 3:
		sys.stdin.readline()

def to_BW(blk):
	n = len(blk)
	BW = [0, 0]
	for i in range(n):
		for j in range(n):
			BW[(i + j + int(blk[i][j])) % 2] += 1
	return BW
BWs = [to_BW(blk) for blk in blks]
res = 4 * n ** 2
for i in range(4):
	for j in range(i):
		kl = list(set(range(4)) - {i, j})
		res = min(res, BWs[i][0] + BWs[j][0] + BWs[kl[0]][1] + BWs[kl[1]][1])
print(res)


n = int(input())
l = list()
for i in range(4):
	l.append([list(input()) for x in range(n)])
	if i < 3:
		input()
lt = [0, 0, 0, 0]
min_f = (n * 2) ** 2
for i in range(1, 4):
	ll = [1, 2, 3]
	lt[1] = ll.pop(i - 1)
	for x in range(2):
		lb = list()
		lt[2] = ll[x]
		lt[3] = ll[x - 1]
		for y in range(n * 2):
			if y < n:
				lb.append(list(map(int, l[lt[0]][y % n] + l[lt[1]][y % n])))
			else:
				lb.append(list(map(int, l[lt[2]][y % n] + l[lt[3]][y % n])))
		for y in range(2):
			f = 0
			for y1 in range(n * 2):
				for x1 in range(n * 2):
					if (x1 + y1) % 2:
						if lb[y1][x1] != y:
							f += 1
					elif lb[y1][x1] == y:
						f += 1
			if f < min_f:
				min_f = f
print(min_f)