Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.

Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.

Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.


-----Input-----

The first line contains two integers n and m, the number of variables and bit depth, respectively (1 ≤ n ≤ 5000; 1 ≤ m ≤ 1000). 

The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of:  Binary number of exactly m bits.  The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter.  

Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.


-----Output-----

In the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.


-----Examples-----
Input
3 3
a := 101
b := 011
c := ? XOR b

Output
011
100

Input
5 1
a := 1
bb := 0
cx := ? OR a
d := ? XOR ?
e := d AND bb

Output
0
0



-----Note-----

In the first sample if Peter chooses a number 011_2, then a = 101_2, b = 011_2, c = 000_2, the sum of their values is 8. If he chooses the number 100_2, then a = 101_2, b = 011_2, c = 111_2, the sum of their values is 15.

For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0.

Difficulty: MEDIUM_HARD
Tags: Bit manipulation

Graph traversal

Implementation

Complete search
Skill types: Bit manipulation

Complete search

Starter code:

Solutions:
def OP(i, j, op):
	if op == 'AND':
		return i & j
	if op == 'OR':
		return i | j
	if op == 'XOR':
		return i ^ j
	return 0

def totbit(i, test):
	ans = 0
	for j in range(0, len(ops)):
		a = ops[j][0]
		b = ops[j][1]
		op = ops[j][2]
		if a == '?':
			x = test
		elif a in M:
			x = int(M[a][i])
		else:
			x = OL[OD[a]]
		if b == '?':
			y = test
		elif b in M:
			y = int(M[b][i])
		else:
			y = OL[OD[b]]
		ans += OP(x, y, op)
		OL[j] = OP(x, y, op)
	return ans
ops = []
[n, m] = list(map(int, input().split()))
M = dict()
OL = []
OD = dict()
for i in range(0, n):
	inp = input().split()
	a = inp[0]
	if len(inp) == 3:
		b = inp[2]
		M[a] = b
	else:
		a = inp[2]
		b = inp[4]
		op = inp[3]
		OD[inp[0]] = len(OL)
		OL.append(0)
		ops.append([a, b, op])
mi = ''
ma = ''
for i in range(0, m):
	b0 = totbit(i, 0)
	b1 = totbit(i, 1)
	if b0 >= b1:
		ma += '0'
	else:
		ma += '1'
	if b0 <= b1:
		mi += '0'
	else:
		mi += '1'
print(mi)
print(ma)


f = {'OR': lambda x, y: x | y, 'AND': lambda x, y: x & y, 'XOR': lambda x, y: x ^ y}
(n, m) = map(int, input().split())
(p, u, v) = ([], [], [])
l = {'?': n}
for i in range(n):
	(q, s) = input().split(' := ')
	if ' ' in s:
		(x, t, y) = s.split()
		p += [(l[x], f[t], l[y])]
		u += [i]
	else:
		p += [int(s, 2)]
		v += [i]
	l[q] = i
s = [0] * (n + 1)

def g(k, l):
	s[n] = k
	for i in v:
		s[i] = p[i] & l > 0
	for i in u:
		(x, f, y) = p[i]
		s[i] = f(s[x], s[y])
	return sum(s) - k
a = b = ''
for j in range(m):
	l = 1 << m - j - 1
	(x, y) = (g(0, l), g(1, l))
	a += '01'[y < x]
	b += '01'[y > x]
print(a, b)


from sys import *
from decimal import *
(n, k) = (int(z) for z in stdin.readline().split())
d = []
nm = [0] * n
bt1 = [False] * (n + 1)
bt2 = [False] * (n + 1)
bt2[-1] = True
nam = dict()
nam['?'] = -1
for i in range(n):
	fl = 0
	s = stdin.readline()[:-1].split(' := ')
	nam[s[0]] = i
	if len(s[1]) < 30:
		for j in s[1]:
			if j == 'A':
				fl = 1
				break
			if j == 'X':
				fl = 2
				break
			if j == 'O':
				fl = 3
				break
	if fl == 0:
		d.append([nam[s[0]], s[1]])
	elif fl == 1:
		d.append([i] + [nam[z] for z in s[1].split(' AND ')])
	elif fl == 2:
		d.append([i] + [nam[z] for z in s[1].split(' XOR ')])
	else:
		d.append([i] + [nam[z] for z in s[1].split(' OR ')])
	nm[i] = fl
mn = [False] * k
mx = [False] * k
for i in range(k):
	r1 = 0
	r2 = 0
	for ololo in range(n):
		eq = d[ololo]
		if nm[ololo] == 0:
			bt1[eq[0]] = bool(int(eq[1][i]))
			r1 += int(eq[1][i])
			bt2[eq[0]] = bool(int(eq[1][i]))
			r2 += int(eq[1][i])
		elif nm[ololo] == 1:
			if bt1[eq[1]] == bt1[eq[2]] == True:
				bt1[eq[0]] = True
				r1 += 1
			else:
				bt1[eq[0]] = False
			if bt2[eq[1]] == bt2[eq[2]] == True:
				bt2[eq[0]] = True
				r2 += 1
			else:
				bt2[eq[0]] = False
		elif nm[ololo] == 2:
			if bt1[eq[1]] != bt1[eq[2]]:
				bt1[eq[0]] = True
				r1 += 1
			else:
				bt1[eq[0]] = False
			if bt2[eq[1]] != bt2[eq[2]]:
				bt2[eq[0]] = True
				r2 += 1
			else:
				bt2[eq[0]] = False
		else:
			if bt1[eq[1]] != bt1[eq[2]] or bt1[eq[2]] != False:
				bt1[eq[0]] = True
				r1 += 1
			else:
				bt1[eq[0]] = False
			if bt2[eq[1]] != bt2[eq[2]] or bt2[eq[2]] != False:
				bt2[eq[0]] = True
				r2 += 1
			else:
				bt2[eq[0]] = False
	if r2 > r1:
		mn[i] = True
	elif r2 < r1:
		mx[i] = True
stdout.write(''.join((str(int(z)) for z in mx)) + '\n')
stdout.write(''.join((str(int(z)) for z in mn)) + '\n')


import sys

def calc(b0, b1, q):
	if q == 0:
		return b0 ^ b1
	if q == 1:
		return b0 | b1
	if q == 2:
		return b0 & b1
(n, m) = map(int, sys.stdin.readline().split())
arr1 = {}
opt = ['XOR', 'OR', 'AND']
arr2 = []
for j in range(n):
	(a, b) = list(map(str, sys.stdin.readline().split(' := ')))
	b = b.split()
	if len(b) == 1:
		s = b[0]
		arr1[a] = s
	else:
		c = b[0]
		d = b[2]
		q = opt.index(b[1])
		arr2.append((a, c, d, q))
mins = ''
maxs = ''
d0 = {'?': 0}
d1 = {'?': 1}
for i in range(m):
	for (a, b) in arr1.items():
		d0[a] = int(b[i])
		d1[a] = int(b[i])
	s0 = 0
	s1 = 0
	for (a, c, d, q) in arr2:
		b00 = d0[c]
		b01 = d0[d]
		b10 = d1[c]
		b11 = d1[d]
		c0 = calc(b00, b01, q)
		c1 = calc(b10, b11, q)
		s0 += 1 if c0 else 0
		s1 += 1 if c1 else 0
		d0[a] = c0
		d1[a] = c1
	if s1 < s0:
		mins += '1'
	else:
		mins += '0'
	if s1 > s0:
		maxs += '1'
	else:
		maxs += '0'
sys.stdout.write('{0}\n{1}'.format(mins, maxs))


def func(b0, b1, op):
	if op == 0:
		return b0 ^ b1
	if op == 1:
		return b0 | b1
	if op == 2:
		return b0 & b1
(n, m) = [int(x) for x in input().split()]
cs = {}
ops = ['XOR', 'OR', 'AND']
fs = []
for j in range(n):
	(name, value) = input().split(' := ')
	value = value.split()
	if len(value) == 1:
		s = value[0]
		cs[name] = s
	else:
		lt = value[0]
		rt = value[2]
		op = ops.index(value[1])
		fs.append((name, lt, rt, op))
mins = ''
maxs = ''
d0 = {'?': 0}
d1 = {'?': 1}
for i in range(m):
	for (name, value) in cs.items():
		d0[name] = int(value[i])
		d1[name] = int(value[i])
	s0 = 0
	s1 = 0
	for (name, lt, rt, op) in fs:
		b00 = d0[lt]
		b01 = d0[rt]
		b10 = d1[lt]
		b11 = d1[rt]
		c0 = func(b00, b01, op)
		c1 = func(b10, b11, op)
		s0 += 1 if c0 else 0
		s1 += 1 if c1 else 0
		d0[name] = c0
		d1[name] = c1
	mins += '1' if s1 < s0 else '0'
	maxs += '1' if s1 > s0 else '0'
print(mins)
print(maxs)


def sumBin(a, b, varMap):
	lhs = varMap[a]
	rhs = varMap[b]
	return bin(int(lhs, 2) + int(rhs, 2))[2:]

def andBin(a, b, varMap):
	lhs = varMap[a]
	rhs = varMap[b]
	return bin(int(lhs, 2) & int(rhs, 2))[2:]

def orBin(a, b, varMap):
	lhs = varMap[a]
	rhs = varMap[b]
	return bin(int(lhs, 2) | int(rhs, 2))[2:]

def xorBin(a, b, varMap):
	lhs = varMap[a]
	rhs = varMap[b]
	return bin(int(lhs, 2) ^ int(rhs, 2))[2:]
mapOper = {'AND': andBin, 'OR': orBin, 'XOR': xorBin}
(n, m) = list(map(int, input().split()))
minMap = {'?': '0', '': '0'}
maxMap = {'?': '1' * m, '': '0'}
minSum = '0'
maxSum = '0'
for _ in range(n):
	(name, _, expr) = input().split(' ', 2)
	if len(expr.split(' ')) == 1:
		minMap[name] = expr
		maxMap[name] = expr
	else:
		(lhs, oper, rhs) = expr.split()
		minMap[name] = mapOper[oper](lhs, rhs, minMap).zfill(m)
		maxMap[name] = mapOper[oper](lhs, rhs, maxMap).zfill(m)
	minSum = sumBin('', name, minMap)
	maxSum = sumBin('', name, maxMap)

def countOnes(i, varMap):
	ones = 0
	for (name, num) in list(varMap.items()):
		if name != '?' and name != '':
			ones += num[i] == '1'
	return ones
minRes = ''
maxRes = ''
for i in range(m):
	zeroOnes = countOnes(i, minMap)
	oneOnes = countOnes(i, maxMap)
	if zeroOnes > oneOnes:
		maxRes += '0'
		minRes += '1'
	elif zeroOnes < oneOnes:
		maxRes += '1'
		minRes += '0'
	else:
		maxRes += '0'
		minRes += '0'
print(minRes)
print(maxRes)


(n, m) = map(int, input().split())
v = [('?', '')]
temp = [(0, 1)]
d = {}
d['?'] = 0
(mn, mx) = ('', '')
for i in range(n):
	(name, val) = input().split(' := ')
	v.append((name, val.split()))
	temp.append((-1, -1))
	d[name] = i + 1

def eval(expr, bit1, bit2):
	if expr == 'OR':
		return bit1 | bit2
	elif expr == 'AND':
		return bit1 and bit2
	elif expr == 'XOR':
		return bit1 ^ bit2
	else:
		raise AttributeError()
for i in range(m):
	for (name, expr) in v[1:]:
		j = d[name]
		if len(expr) == 1:
			temp[j] = (int(expr[0][i]), int(expr[0][i]))
		else:
			(bit1, bit2) = (temp[d[expr[0]]], temp[d[expr[2]]])
			temp[j] = (eval(expr[1], bit1[0], bit2[0]), eval(expr[1], bit1[1], bit2[1]))
	(z, o) = (sum((temp[_][0] for _ in range(1, n + 1))), sum((temp[_][1] for _ in range(1, n + 1))))
	mn += '1' if o < z else '0'
	mx += '1' if o > z else '0'
print(mn)
print(mx)


(n, m) = map(int, input().split())
vars = {}

def mxor(a, b):
	if a == b:
		return '0'
	elif a == '0' and b == '1' or (a == '1' and b == '0'):
		return '1'
	elif a == '0' and b == 'x' or (a == 'x' and b == '0'):
		return 'x'
	elif a == '0' and b == '!' or (a == '!' and b == '0'):
		return '!'
	elif a == '1' and b == 'x' or (a == 'x' and b == '1'):
		return '!'
	elif a == '1' and b == '!' or (a == '!' and b == '1'):
		return 'x'
	elif a == 'x' and b == '!' or (a == '!' and b == 'x'):
		return '1'

def mand(a, b):
	if a == b:
		return a
	elif a == '0' or b == '0':
		return '0'
	elif a == '1' and b == 'x' or (a == 'x' and b == '1'):
		return 'x'
	elif a == '1' and b == '!' or (a == '!' and b == '1'):
		return '!'
	elif a == 'x' and b == '!' or (a == '!' and b == 'x'):
		return '0'

def mor(a, b):
	if a == b:
		return a
	if a == '1' or b == '1':
		return '1'
	elif a == '0':
		return b
	elif b == '0':
		return a
	elif a == 'x' and b == '!' or (a == '!' and b == 'x'):
		return '1'

def calc(a, op, b):
	global m
	global vars
	a = ['x'] * m if a == '?' else vars[a]
	b = ['x'] * m if b == '?' else vars[b]
	if op == 'XOR':
		op = mxor
	elif op == 'AND':
		op = mand
	else:
		op = mor
	return ''.join([op(x, y) for (x, y) in zip(a, b)])
for _ in range(n):
	i = input().split()
	if len(i) == 3:
		vars[i[0]] = i[2]
	else:
		vars[i[0]] = calc(*i[2:])
r = [0] * m
for i in range(m):
	for v in vars.values():
		if v[i] == 'x':
			r[i] += 1
		elif v[i] == '!':
			r[i] -= 1
mmin = ['0'] * m
mmax = ['0'] * m
for i in range(m):
	if r[i] < 0:
		mmin[i] = '1'
for i in range(m):
	if r[i] > 0:
		mmax[i] = '1'
print(''.join(mmin))
print(''.join(mmax))