每个指令和目标线程号分别存储在两个列表
from collections import deque
class threadMsg:
def __init__(self):
self.cmd_list = deque()
self.target_id_list = deque()
def pop(self):
if len(self) != 0:
self.cmd_list.popleft()
self.target_id_list.popleft()
def __len__(self):
return len(self.cmd_list)
def getMsg(self):
return (self.cmd_list[0], self.target_id_list[0]) if len(self) else (None, None)
def getMsg(n):
msg_que = []
for _ in range(n):
thread = threadMsg()
one_line = input()
for cmd_str in one_line.split():
thread.cmd_list.append(cmd_str[:1])
thread.target_id_list.append(int(cmd_str[1:]))
msg_que.append(thread)
return msg_que
# 当前进程能否和其它进程通信,并且会消耗消息(如果通信成功)
def comOnce(msg_que, idx):
cur_cmd, cur_target = msg_que[idx].getMsg()
if cur_cmd == None:
return False
tar_cmd, tar_target = msg_que[cur_target].getMsg()
if tar_cmd == None:
return False
t = cur_cmd + tar_cmd
if tar_target == idx and (t == "RS" or t == "SR"):
msg_que[idx].pop()
msg_que[cur_target].pop()
return True
return False
def isLocked(msg_que):
while True:
# 遍历一次所有进程,判断能否和其它进程通信
failed = True
for i, thread_obj in enumerate(msg_que):
if comOnce(msg_que, i):
failed = False
# 统计非空线程数目
noMsgThrCnt = 0
for thread in msg_que:
if len(thread) == 0:
noMsgThrCnt += 1
if noMsgThrCnt == len(msg_que):
return False
if failed:
return True
if __name__ == '__main__':
T, n = map(int, input().split())
for _ in range(T):
msg_que = getMsg(n)
if isLocked(msg_que):
print(1)
else:
print(0)