import re
def NOT(a):
return (a+1)%2
def AND(a,b,*c):
ans=a and b
if not c:
return ans
for i in c:
if ans==0:
return ans
else:
ans=ans and i
return ans
def OR(a,b,*c):
ans=a or b
if not c:
return ans
for i in c:
if ans==1:
return ans
else:
ans=ans or i
return ans
def XOR(a,b,*c):
ans=(a+b)%2
if not c:
return ans
for i in c:
ans=(ans+i)%2
return ans
def NAND(a,b,*c):
return (AND(a,b,*c)+1)%2
def NOR(a,b,*c):
return (OR(a,b,*c)+1)%2
def read_oneline_int():
s=re.findall('-?\d+',input())
for i in range(len(s)):
s[i]=int(s[i])
return s
def read_oneline_func():
s=re.split(' ',input())
return s
Q=int(input())
#检查结果是否计算出来,若是则输出结果,并返回True
def check_ans_exist(known,output_des):
for i in output_des[1:]:
if not ('O'+str(i) in known):
return 0
for i in output_des[1:]:
print(known['O'+str(i)],end=" ")
print() #print本身自带一个\n,因此不要使用print("\n")
return 1
#解决回路:每次遍历一次用到的函数,如果没有新的结果出来,而且目标还没算出来,说明有回路,返回0
def run(input_des,output_des,func_list):
#运行一次电路
known={}
not_execute_list={}
for i in range(len(func_list)):
not_execute_list['O'+str(i+1)]=func_list[i]
while(1):
to_be_del=[]
#遍历运行没运行过函数
for i in not_execute_list:
parameter=[]
#初始化参数列表
for j in not_execute_list[i][2:]:
if j[0]=='I':
parameter.append(input_des[int(re.findall('\d+',j)[0])-1])
elif j[0]=='O':
if j in known:
parameter.append(known[j])
else:
break
if len(parameter)==int(not_execute_list[i][1]):
if not_execute_list[i][0]=='XOR':
known[i]=XOR(*tuple(parameter))
elif not_execute_list[i][0]=='OR':
known[i]=OR(*tuple(parameter))
elif not_execute_list[i][0]=='AND':
known[i]=AND(*tuple(parameter))
elif not_execute_list[i][0]=='NAND':
known[i]=NAND(*tuple(parameter))
elif not_execute_list[i][0]=='NOR':
known[i]=NOR(*tuple(parameter))
elif not_execute_list[i][0]=='NOT':
known[i]=NOT(*tuple(parameter))
to_be_del.append(not_execute_list[i])
#该轮执行没有新结果,有回路
if len(to_be_del)==0:
return 0
#执行出来结果了,不用再执行了
if check_ans_exist(known,output_des):
break
for i in to_be_del:
del not_execute_list[i]
return 1
def resolve_question():
#解决一个问题
M,N=tuple(read_oneline_int())
func_list=[]
for i in range(N):
func_list.append(read_oneline_func())
S=int(input())
input_descri=[]
output_descri=[]
for i in range(S):
input_descri.append(read_oneline_int())
for i in range(S):
output_descri.append(read_oneline_int())
for i in range(S):
if not run(input_descri[i],output_descri[i],func_list):
print('LOOP')
break
for i in range(Q):
resolve_question()